在JDK7、8版本中用 ImageIO.write进行图片输出时,如果输出PNG格式图片非常的缓慢
Poor performances of imwrite, especially for png extension.
上代码-解决前:
@Test
public void testWirte() throws Exception {
String dir = "/Users/user/Downloads/testimg/";
final MockMultipartFile file = new MockMultipartFile("big5.png", new FileInputStream(new File(dir + "big5.png")));
final BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
long start = System.currentTimeMillis();
ImageIO.write(bufferedImage,"png",new FileOutputStream(new File(dir + "/out/big5-out.png")));
System.out.println((System.currentTimeMillis() - start) + " ms ");
}
5198 ms
解决后:
@Test
public void testWirte1() throws Exception {
String dir = "/Users/user/Downloads/testimg/";
final MockMultipartFile file = new MockMultipartFile("big5.png", new FileInputStream(new File(dir + "big5.png")));
final BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
long start = System.currentTimeMillis();
ImageWriter writer = ImageIO.getImageWritersByFormatName("png").next();
ImageWriteParam writeParam = writer.getDefaultWriteParam();
writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
writeParam.setCompressionQuality(0.9f);
final FileImageOutputStream stream = new FileImageOutputStream(new File(dir + "/out/big5-out.png"));
try {
writer.setOutput(stream);
writer.write(null, new IIOImage(bufferedImage, null, null), writeParam);
} finally {
stream.close();
writer.dispose();
}
System.out.println((System.currentTimeMillis() - start) + " ms ");
}
2127 ms
测试图片说明:5.7M png格式
问题说明:
这是一个JDK7、8ImageIO的一个BUG,在9进行了修复,详情参加
1.下载jdk9-png-writer-backport源码
https://github.com/gredler/jdk9-png-writer-backporthttps://github.com/gredler/jdk9-png-writer-backport2.把对应内容打包到私仓或者直接copy至项目目录
其他方案:
pngencoderhttps://hub.xn--gzu630h.xn--kpry57d/pngencoder/pngencoder
这个目前还在测试中,速度优于上面的方案