一、前言
整理笔记时,看到个曾经用到的图片进行压缩代码,分享给大家
二、相关代码
/***
* @Description : 创建缩略图
* @param filename 原图文件路径
* @param width 压缩宽度
* @param height 压缩高度
* @param quality 压缩像素
* @param outFilename 压缩后的文件路径
* @return void
*/
public static void createThumbnail(String filename, int width, int height, int quality, String outFilename) throws InterruptedException, IOException {
// 从文件名加载图像
Image image = Toolkit.getDefaultToolkit().getImage(filename);
MediaTracker mediaTracker = new MediaTracker(new Container());
mediaTracker.addImage(image, 0);
mediaTracker.waitForID(0);
// 根据宽度和高度确定缩略图大小
double thumbRatio = (double) width / (double) height;
int imageWidth = image.getWidth(null);
int imageHeight = image.getHeight(null);
double imageRatio = (double) imageWidth / (double) imageHeight;
if (thumbRatio < imageRatio) {
height = (int) (width / imageRatio);
} else {
width = (int) (height * imageRatio);
}
// 将原始图像绘制到缩略图图像对象,将其缩放到新尺寸
BufferedImage thumbImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = thumbImage.createGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics2D.drawImage(image, 0, 0, width, height, null);
// 将缩略图图像保存到新的路径下
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFilename));
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);
quality = Math.max(0, Math.min(quality, 100));
param.setQuality((float) quality / 100.0f, false);
encoder.setJPEGEncodeParam(param);
encoder.encode(thumbImage);
out.close();
}
三、测试示例
public static void main(String... args) throws Exception{
String filename="D:\\test.jpeg";
String outFilename="D:\\test2.jpeg";
createThumbnail(filename,100,100,100,outFilename);
}