Java压缩图片工具类 悟寰轩

 1 import java.awt.Image;
 2 import java.awt.image.BufferedImage;
 3 import java.io.File;
 4 import java.io.FileOutputStream;
 5 import java.io.IOException;
 6 
 7 import javax.imageio.ImageIO;
 8 
 9 import org.slf4j.Logger;
10 import org.slf4j.LoggerFactory;
11 
12 import com.sun.image.codec.jpeg.JPEGCodec;
13 import com.sun.image.codec.jpeg.JPEGImageEncoder;
14 public class CompressPicUtils {
15 private static final Logger logger = LoggerFactory.getLogger(CompressPicUtils.class);
16 private File inputFile; // 文件对象
17 private File outputFile; // 输出图路径
18 private int outputWidth; // 默认输出图片宽
19 private int outputHeight; // 默认输出图片高
20 private boolean proportion = true; // 是否等比缩放标记(默认为等比缩放)
21 public CompressPicUtils() {
22 }
23 public boolean compressPic() {
24 try {
25 // 获得源文件
26 if (!inputFile.exists()) {
27 return false;
28 }
29 Image img = ImageIO.read(inputFile);
30 // 判断图片格式是否正确
31 if (img.getWidth(null) == -1) {
32 return false;
33 } else {
34 int newWidth;
35 int newHeight;
36 // 判断是否是等比缩放
37 if (this.proportion == true) {
38 // 为等比缩放计算输出的图片宽度及高度
39 double rate1 = ((double) img.getWidth(null)) / (double) outputWidth + 0.1;
40 double rate2 = ((double) img.getHeight(null)) / (double) outputHeight + 0.1;
41 // 根据缩放比率大的进行缩放控制
42 double rate = rate1 > rate2 ? rate1 : rate2;
43 newWidth = (int) (img.getWidth(null) / rate);
44 newHeight = (int) (img.getHeight(null) / rate);
45 } else {
46 newWidth = outputWidth; // 输出的图片宽度
47 newHeight = outputHeight; // 输出的图片高度
48 }
49 BufferedImage tag = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
50 tag.getGraphics().drawImage(img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), 0, 0, null);
51 FileOutputStream out = new FileOutputStream(outputFile);
52 // JPEGImageEncoder可适用于其他图片类型的转换
53 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
54 encoder.encode(tag);
55 out.close();
56 }
57 } catch (IOException ex) {
58 logger.error("compressPic error", ex);
59 return false;
60 }
61 return true;
62 }
63 public boolean compressPic(File inputFile, File outputFile, int width, int height, boolean gp) {
64 // 输入图路径
65 this.inputFile = inputFile;
66 // 输出图路径
67 this.outputFile = outputFile;
68 // 设置图片长宽
69 this.outputWidth = width;
70 this.outputHeight = height;
71 // 是否是等比缩放 标记
72 this.proportion = gp;
73 return compressPic();
74 }
75 }
原文地址:https://www.cnblogs.com/sunxucool/p/2799993.html