java 压缩图片工具

因朋友需要帮忙压缩一些图片,手写了一个简单的图片压缩工具类,以下是简单的代码实现,希望能对各位有所帮助。
package cn.com.taiji.integrated.service.impl;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

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

/**
 * @author kongxz
 * @description:
 * @date 2023/11/6
 */
public class ImgCompress {

    static BufferedImage img = null;
    public static void main(String[] args) throws IOException {
        String fromPic = "C:\\Users\\dd\\Desktop\\xxx.jpg";
        String toPic = "C:\\Users\\dd\\Desktop\\xxx-压缩后.jpg";
        ImgCompress imgCom = new ImgCompress(fromPic );
        // 设置压缩后的图片大小为原始图片的一半
        // 读取原始图片
        BufferedImage originalImage = ImageIO.read(new File("C:\\Users\\dd\\Desktop\\xxx.jpg"));
        //获取当前图片宽度,也可以自定义
        int newWidth = originalImage.getWidth();
        //获取当前图片高度,也可以自定义
        int newHeight = originalImage.getHeight();

        //图片质量需设置在0.1-1范围
        float quality = (float) 0.1;

        imgCom.resize(newWidth, newHeight, toPic,quality);
    }

    /**
     * 构造函数
     */
    public ImgCompress(String fileName) throws IOException {
        File file = new File(fileName);// 读入文件
        img = ImageIO.read(file);      // 构造Image对象
    }

    /**
     * 强制压缩/放大图片到固定的大小
     *
     * @param w int 新宽度
     * @param h int 新高度
     */
    public void resize(int w, int h, String toPic,float quality) throws IOException {
        // SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的 优先级比速度高 生成的图片质量比较好 但速度慢
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        image.getGraphics().drawImage(img, 0, 0, w, h, null); // 绘制缩小后的图
        File destFile = new File(toPic);
        if (quality > 1) {
            throw new IllegalArgumentException(
                    "图片质量需设置在0.1-1范围");
        }
        FileOutputStream out = new FileOutputStream(destFile); // 输出到文件流
        // 可以正常实现bmp、png、gif转jpg
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        encoder.encode(image); // JPEG编码

        //控制压缩质量  如果不需要 注释掉 默认压缩
        JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(image);
        param.setQuality(quality, true);
        encoder.setJPEGEncodeParam(param);
        encoder.encode(image);

        out.close();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值