图片压缩工具类

本文介绍了一个用于图片压缩的Java工具类,该工具可以根据指定的宽度、高度及质量参数压缩图片,并将压缩后的图片保存到新的文件路径中。文章通过示例展示了如何使用此工具类来压缩一张名为20210302134405.jpg的图片。

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.imageio.ImageIO;

/**
 * 图片压缩
 */
public class ImageZipUtil {
  public static void main(String[] args) throws Exception{
    File oldFile=new File("F:\\1\\20210302134405.jpg");
    String newFilePath="F:\\1\\20210302134405_1.jpg";
    BufferedImage bufferedImg = ImageIO.read(oldFile);
    int width=(int) (bufferedImg.getWidth()*0.6f);
    int height=(int) (bufferedImg.getHeight()*0.6f);
    String imagpath = zipWidthHeightImageFile(oldFile,newFilePath,width,height,0.7f);
    System.out.println("==imagpath="+imagpath);
  }

/**
   * 按设置的宽度高度压缩图片文件<br> 先保存原文件,再压缩、上传
   * @param oldFile 要进行压缩的文件全路径
   * @param newFile 新文件存放路径
   * @param width 宽度
   * @param height 高度
   * @param quality 质量
   * @return 返回压缩后的文件的全路径
   */
  public static String zipWidthHeightImageFile(File oldFile,String newFilePath,int width, int height,float quality) {
        if (oldFile == null) {
            return null;
        }
        
        Image srcFile = null;
        BufferedImage buffImg = null;

        try {
            /** 对服务器上的临时文件进行处理 */
            srcFile = ImageIO.read(oldFile);
            System.out.println("输出新的较片路径:" + newFilePath);
            String subfix = "jpg";
            subfix = newFilePath.substring(newFilePath.lastIndexOf(".") + 1, newFilePath.length());
            if (subfix.equals("png")) {
                buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
            } else {
                buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            }
            Graphics2D graphics = buffImg.createGraphics();
            graphics.setBackground(new Color(255, 255, 255));
            graphics.setColor(new Color(255, 255, 255));
            graphics.fillRect(0, 0, width, height);
            graphics.drawImage(srcFile.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
            File newFile = new File(newFilePath);
            ImageIO.write(buffImg, subfix, newFile);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (srcFile != null) {
                srcFile.flush();
            }
            if (buffImg != null) {
                buffImg.flush();
            }
        }
        return newFilePath;
    }

 

 

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值