Posted on 2016-09-23 14:08
魔のkyo 阅读(318)
评论(0) 编辑 收藏 引用
实现
private void convertImage(File srcFile, File dstFile, String dstFormat, Integer width, Integer height) throws Exception {
BufferedImage src = ImageIO.read(srcFile);
if(width == null && height == null) {
width = src.getWidth();
height = src.getHeight();
}
else if(width != null && height == null) {
height = (int)(1.0 * width * src.getHeight() / src.getWidth() + 0.5);
}
else if(height != null && width == null) {
width = (int)(1.0 * height * src.getWidth() / src.getHeight() + 0.5);
}
BufferedImage dst = new BufferedImage(
width, height,
src.getType());
Graphics2D g2d = dst.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.drawImage(src.getScaledInstance(width, height, java.awt.Image.SCALE_SMOOTH),
0, 0, width, height, null);
g2d.dispose();
ImageIO.write(dst, dstFormat, dstFile);
}
用例
convertImage(new File("D:\\test.jpg"), new File("D:\\test.png"), "png", null, null); // jpg转png格式
convertImage(new File("D:\\test.jpg"), new File("D:\\test2.jpg"), "jpg", 256, null); // 固定长宽比缩放
convertImage(new File("D:\\test.jpg"), new File("D:\\test3.jpg"), "jpg", 256, 512); // 指定长宽拉伸缩放
因为带缩放,注意一定要用Image.SCALE_SMOOTH,否则会出现失真。