import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.io.File;
import java.io.FileOutputStream;
/**
* @Description 图片压缩
*/
public class ImgUtil {
private static final Logger logger = LoggerFactory.getLogger(ImgUtil.class);
public static void main(String[] args) {
ImgUtil imgUtil = new ImgUtil();
imgUtil.imgCompress("D:\\Picture\\桌面壁纸\\006.jpg", "d:/test.jpg", 200, 112);
System.out.println("压缩完成....");
}
public void imgCompress(String sourcePath, String targetPath, int width, int height) {
this.imgCompress(new File(sourcePath), new File(targetPath), width, height);
}
public void imgCompress(File sourceFile, File targetFile, int width, int height) {
try {
Image image = javax.imageio.ImageIO.read(sourceFile);
image = image.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING);
// 生成图像Buffer
BufferedImage mBufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = mBufferedImage.createGraphics();
graphics.drawImage(image, 0, 0, width, height, Color.white, null);
graphics.dispose();
float[] kernelData = {-0.125f, -0.125f, -0.125f, -0.125f, 2, -0.125f, -0.125f, -0.125f, -0.125f};
Kernel kernel = new Kernel(3, 3, kernelData);
ConvolveOp convolveOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
mBufferedImage = convolveOp.filter(mBufferedImage, null);
File targetDir = targetFile.getParentFile();
if (!targetDir.exists()) {
targetDir.mkdirs();
}
FileOutputStream out = new FileOutputStream(targetFile);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(mBufferedImage);
out.close();
} catch (Exception e) {
logger.error("图片压缩出错 - sourceFile=" + sourceFile.getPath() + ", targetPath=" + targetFile.getPath()
+ ", width=" + width + ", height=" + height, e);
}
}
}
来源:CSDN
作者:MarketStream
链接:https://blog.csdn.net/shizhenbang01/article/details/103734331