第一次写博客 有点小紧张...
最近负责一个图片合成的功能,因为商品主图太大,合成后的图片有1MB多。
首先我得感谢一位大佬,如果没有他Image类转换BufferedImage类的工具,我可能明天早上才能睡觉了。
我推荐使用:谷歌图片处理插件(Thumbnailator)
pom的jar包依赖:
<!-- 图片处理 -->
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
添加jar包后,编写工具类:
/**
* @author kcy
* @version 2018-11-8
* @param imgsrc 原图片路径
* @param imgdist 压缩后新文件路径
* @param width 宽
* @param height 高
* @param quality 图片质量 (0 - 1.0f)浮点型
*/
public void ImageCompression(String oldImg,String newsImg,int width, int height, Float quality) throws IOException {
/**
Thumbnails.of() <- 这个方法虽然可以直接使用原图路径读取图片,但是有很大几率会使压缩后的图片颜色失真。
也建议不要用ImageIO.read()这种方法读取图片,灰常容易失真!
**/
//使用Toolkit.getDefaultToolkit().getImage()读取图片,防止图片颜色失真。
Image image = Toolkit.getDefaultToolkit().getImage(oldImg);
//Image转换BufferedImage
BufferedImage bufferedImage = this.toBufferedImage(image);
//图片压缩
Thumbnails.of(bufferedImage).
//新图片宽高
size(width, height).
//新图片后缀
outputFormat(“jpg”).
//保持长宽比例
keepAspectRatio(false).
//压缩质量
outputQuality(quality).
//新图片路径
toFile(newsImg);
}
再加上Image转换BufferedImage的方法:
public BufferedImage toBufferedImage(Image image) {
if (image instanceof BufferedImage) {
return (BufferedImage) image;
}
// This code ensures that all the pixels in the image are loaded
image = new ImageIcon(image).getImage();
BufferedImage bimage = null;
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
try {
int transparency = Transparency.OPAQUE;
GraphicsDevice gs = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gs.getDefaultConfiguration();
bimage = gc.createCompatibleImage(image.getWidth(null), image.getHeight(null), transparency);
} catch (HeadlessException e) {
// The system does not have a screen
}
if (bimage == null) {
// Create a buffered image using the default color model
int type = BufferedImage.TYPE_INT_RGB;
bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
}
// Copy image to buffered image
Graphics g = bimage.createGraphics();
// Paint the image onto the buffered image
g.drawImage(image, 0, 0, null);
g.dispose();
return bimage;
}
压缩完成,减小图片颜色失真率,可以下班啦,美滋滋。
再次感觉编写Image类转换BufferedImage类的工具的大佬,谢谢,谢谢!。