美文网首页学习工具类
java图片压缩工具类(指定压缩大小)

java图片压缩工具类(指定压缩大小)

作者: 星钻首席小管家 | 来源:发表于2021-08-04 16:36 被阅读0次

    转载:java图片压缩工具类(指定压缩大小) - 一个九零後的程序猿 - 博客园 (cnblogs.com)

    1:先导入依赖

    <!--thumbnailator图片处理-->
            <dependency>
                <groupId>net.coobird</groupId>
                <artifactId>thumbnailator</artifactId>
                <version>0.4.8</version>
            </dependency>
    

    2:创建工具类--->PicUtils

    import net.coobird.thumbnailator.Thumbnails;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    
    /**
     * @PROJECT_NAME: water_chivalry
     * @AUTHOR: Hanson-Hsc
     * @DATE: 2020-07-27 09:08
     * @DESCRIPTION: 图片压缩工具
     * @VERSION:
     */
    public class PicUtils {
      //以下是常量,按照阿里代码开发规范,不允许代码中出现魔法值
        private static final Logger logger = LoggerFactory.getLogger(PicUtils.class);
        private static final Integer ZERO = 0;
        private static final Integer ONE_ZERO_TWO_FOUR = 1024;
        private static final Integer NINE_ZERO_ZERO = 900;
        private static final Integer THREE_TWO_SEVEN_FIVE = 3275;
        private static final Integer TWO_ZERO_FOUR_SEVEN = 2047;
        private static final Double ZERO_EIGHT_FIVE = 0.85;
        private static final Double ZERO_SIX = 0.6;
        private static final Double ZERO_FOUR_FOUR = 0.44;
        private static final Double ZERO_FOUR = 0.4;
    
        /**
         * 根据指定大小压缩图片
         *
         * @param imageBytes  源图片字节数组
         * @param desFileSize 指定图片大小,单位kb
         * @return 压缩质量后的图片字节数组
         */
        public static byte[] compressPicForScale(byte[] imageBytes, long desFileSize) {
            if (imageBytes == null || imageBytes.length <= ZERO || imageBytes.length < desFileSize * ONE_ZERO_TWO_FOUR) {
                return imageBytes;
            }
            long srcSize = imageBytes.length;
            double accuracy = getAccuracy(srcSize / ONE_ZERO_TWO_FOUR);
            try {
                while (imageBytes.length > desFileSize * ONE_ZERO_TWO_FOUR) {
                    ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream(imageBytes.length);
                    Thumbnails.of(inputStream)
                            .scale(accuracy)
                            .outputQuality(accuracy)
                            .toOutputStream(outputStream);
                    imageBytes = outputStream.toByteArray();
                }
                logger.info("图片原大小={}kb | 压缩后大小={}kb",
                        srcSize / ONE_ZERO_TWO_FOUR, imageBytes.length / ONE_ZERO_TWO_FOUR);
            } catch (Exception e) {
                logger.error("【图片压缩】msg=图片压缩失败!", e);
            }
            return imageBytes;
        }
    
        /**
         * 自动调节精度(经验数值)
         *
         * @param size 源图片大小
         * @return 图片压缩质量比
         */
        private static double getAccuracy(long size) {
            double accuracy;
            if (size < NINE_ZERO_ZERO) {
                accuracy = ZERO_EIGHT_FIVE;
            } else if (size < TWO_ZERO_FOUR_SEVEN) {
                accuracy = ZERO_SIX;
            } else if (size < THREE_TWO_SEVEN_FIVE) {
                accuracy = ZERO_FOUR_FOUR;
            } else {
                accuracy = ZERO_FOUR;
            }
            return accuracy;
        }
    }
    

    3:在上传图片接口处进行压缩
    /**
    * 图片上传(招租广告图片专用入口)
    */
    @PostMapping("file/img")
    @ApiOperation(value = "图片上传接口(广告图片专用入口)")public ResultVo imgUploads(@RequestParam("file") MultipartFile file) throws IOException {
    //压缩图片到指定120K以内,不管你的图片有多少兆,都不会超过120kb,精度还算可以,不会模糊
    byte[] bytes = PicUtils.compressPicForScale(file.getBytes(), 120);
    ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
    //生成保存在服务器的图片名称,统一修改原后缀名为:jpg
    String newFileName = UUID.randomUUID() + ".jpg";
    OSSUtil.upload2(newFileName, inputStream);
    JSONObject result = new JSONObject();
    result.put("url", OSSUtil.getUrl2(newFileName, ""));
    return ResultVoUtil.success(result);
    }

    4.还有一个压缩图片工具类,但是不能指定压缩大小,可是很有用,压缩不会丢失精度,图片也很清晰:
    

    import com.bamboo.water_chivalry.common.enums.ResultEnum;
    import com.bamboo.water_chivalry.common.exception.GlobalException;
    import org.springframework.web.multipart.MultipartFile;
    import javax.imageio.ImageIO;
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;

    /**

    • @PROJECT_NAME: water_chivalry

    • @AUTHOR: Hanson-Hsc

    • @DATE: 2020-07-20 09:24

    • @DESCRIPTION: 图片压缩工具

    • @VERSION:
      */
      public class ImgCompression {

      public static InputStream getImageCom(MultipartFile file) throws IOException {
      //获取文件输入流
      InputStream inputStream = file.getInputStream();
      try {
      // 把图片读入到内存中
      BufferedImage bufImg = ImageIO.read(inputStream);
      // 压缩代码,存储图片文件byte数组
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      //防止图片变红,这一步非常重要
      BufferedImage bufferedImage = new BufferedImage(bufImg.getWidth(), bufImg.getHeight(), BufferedImage.TYPE_INT_RGB);
      bufferedImage.createGraphics().drawImage(bufImg,0,0, Color.WHITE,null);
      //先转成jpg格式来压缩,然后在通过OSS来修改成源文件本来的后缀格式
      ImageIO.write(bufferedImage,"jpg",bos);
      //获取输出流
      inputStream = new ByteArrayInputStream(bos.toByteArray());
      return inputStream;
      } catch (IOException e) {
      e.printStackTrace();
      throw new GlobalException(ResultEnum.IMG_UPLOAD_ERROR);
      }finally {
      inputStream.close();
      }
      }
      }

    相关文章

      网友评论

        本文标题:java图片压缩工具类(指定压缩大小)

        本文链接:https://www.haomeiwen.com/subject/plvuvltx.html