Java压缩图片

压缩图片

import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

/**
*  支持常见的图片格式(.jpg、.jpeg、.png.....)
*  srcFil(原路径)如:D:/project/a.png、 outFile(输出路径)如:D:/project/b.png
*  compressRatio:压缩比例为0.5,数字越大压缩程度越小
*  imgeType :图片格式
**/
public static void compressImage(File srcFile, File outFile, double compressRatio,String imgeType) throws IOException {
    BufferedImage srcImage = ImageIO.read(srcFile);
    int width = (int) (srcImage.getWidth() * compressRatio);
    int height = (int) (srcImage.getHeight() * compressRatio);
    BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = resizedImage.createGraphics();
    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g.drawImage(srcImage, 0, 0, width, height, null);
    g.dispose();
    //如果对压缩后的图片格式没有要求的话这里的“imgeType”可以写死为“jpg"
    //就可以压缩.heic、.ico、.raw,也就是先转成.jpg再变回去原格式
    ImageIO.write(resizedImage, imgeType, outFile);
  }
  
  
  public static void main(String[] args) throws IOException {
    File srcFile = new File("D:/project/..");
    File outFile = new File("D:/project/..");
    // 压缩比例为0.5,数字越大压缩程度越小
    compressImage(srcFile, outFile, 0.5,"原图片的格式或者写死,按自己需求,写死支持的格式多"); 
  }
  • 14
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

霜!!

不错,👆赏!!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值