对图片进行压缩,长宽不变(可设置),压缩后不变色写法,亲测写法

 

 All rights reserved.No part of this article may be reproduced or distributed by any means,or stored in a database or retrieval system,without the prior written permission of persistenceGoing author
 

https://blog.youkuaiyun.com/persistencegoing/article/details/84376427

/**
 * 对图片进行压缩
 * @param imgsrc    源图片地址(已存在)
 * @param imgdist    目标图片地址(不存在,但压缩后保存的地址)
 * @param rate     压缩的比例
    * @Author   xrj              
 */
public static void reduceImg(String imgsrc, String imgdist, Float rate) throws IOException{
   File srcfile = new File(imgsrc);
   if (!srcfile.exists()) {
      log.error("Not Found Img File,文件不存在");
      throw new MyException(ResultEnum.ST_FILES_IMAGE_NULL);
   }
   if(rate == null || rate < 0){
      log.error("压缩的比例必须大于0");
      throw new MyException(ResultEnum.ST_FILES_IMAGE_NULL);
   }
   int widthdist,  heightdist=0;
   //获得源图片的宽高存入数组中
   int[] results = getImgWidthHeight(srcfile);
   if (results == null || results[0] == 0 || results[1] == 0) {
      throw new MyException("500","图片异常,请联系管理员");
   } else {
      //按比例缩放或扩大图片大小,将浮点型转为整型
      widthdist = (int) (results[0] * rate);
      heightdist = (int) (results[1] * rate);
   }

   try {
      // 开始读取文件并进行压缩
      Image src = ImageIO.read(srcfile);
      // 构造一个类型为预定义图像类型之一的 BufferedImage
      BufferedImage tag = new BufferedImage((int) widthdist, (int) heightdist, BufferedImage.TYPE_INT_RGB);
      //绘制图像  getScaledInstance表示创建此图像的缩放版本,返回一个新的缩放版本Image,按指定的width,height呈现图像
      //Image.SCALE_SMOOTH,选择图像平滑度比缩放速度具有更高优先级的图像缩放算法。
      tag.getGraphics().drawImage(src.getScaledInstance(widthdist, heightdist, Image.SCALE_SMOOTH), 0, 0, null);
      String formatName = imgdist.substring(imgdist.lastIndexOf(".") + 1);
      File file = new File(imgdist);
      ImageIO.write(tag,formatName,file);

   } catch (Exception ef) {
      log.error("图片压缩错误:"+ef.getMessage());
   }
}



/**
 * 获取图片宽度和高度
 * @Author   xrj
    * @param
 * @return 返回图片的宽度
 */
public static int[] getImgWidthHeight(File file) throws IOException{
   InputStream is = null;
   BufferedImage src = null;
   int result[] = { 0, 0 };
   try {
      // 获得文件输入流
      is = new FileInputStream(file);
      // 从流里将图片写入缓冲图片区
      src = ImageIO.read(is);
      // 得到源图片宽
      result[0] =src.getWidth(null);
      // 得到源图片高
      result[1] =src.getHeight(null);
   } catch (Exception ef) {
      log.error("获取图片宽度和高度:"+ef.getMessage());
   }finally {
      is.close();
   }

   return result;
}

 

 

希望大家关注我一波,防止以后迷路,有需要的可以加群讨论互相学习java ,学习路线探讨,经验分享与java求职     

群号:721 515 304

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值