因朋友需要帮忙压缩一些图片,手写了一个简单的图片压缩工具类,以下是简单的代码实现,希望能对各位有所帮助。
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(); } }