先看下效果图
1.PNG
/**
* 图片压缩处理.
*/
public final class ImgCompressUtil {
private ImgCompressUtil() {
}
/**
* 强制压缩/放大图片到固定的大小.
*
* @param fileName 压缩文件("d:\\1.png")
* @param compressPercent 压缩比例(压缩为原来一半传0.5)
* @return BufferedImage bufferImage
*/
public static BufferedImage resize(String fileName, double compressPercent) {
BufferedImage img = null; //原图
BufferedImage compressImg = null; //压缩后图
int width;
int height;
try {
File file = new File(fileName);
img = ImageIO.read(file);
width = (int) (img.getWidth() * compressPercent);
height = (int) (img.getHeight() * compressPercent);
compressImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
compressImg.getGraphics().drawImage(img, 0, 0, width, height, null); // 绘制缩小后的图
} catch (IOException e) {
e.printStackTrace();
}
return compressImg;
}
/**
* bufferImage 转 file.
*
* @param file 存放位置("d: \\1.png")
* @param img buggerImage
*/
public static void writeToFile(String file, BufferedImage img) {
try {
File destFile = new File(file);
FileOutputStream out = new FileOutputStream(destFile); // 输出到文件流
ImageIO.write(img, "png", out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
测试
@Test
public void pictureCompress() {
String fileName = "D:\\cp.png";
BufferedImage bufferedImage = ImgCompressUtil.resize("D:\\1.png", 0.5);
ImgCompressUtil.writeToFile(fileName + "_middle.png", bufferedImage);
BufferedImage bufferedImage2 = ImgCompressUtil.resize("D:\\1.png", 0.25);
ImgCompressUtil.writeToFile(fileName + "_small.png", bufferedImage2);
}
这里有个小技巧,也就是默认的约定,0.5倍缩略图的名字就是原图名字+_middle.png,0.25倍缩略图的名字就是原图名字+_small.png
网友评论