解决Java处理图像时可能变红、变色问题
...省略上下文代码
URL url = new URL(url);
/* Java上传图片时,对某些图片进行缩放、裁剪或者生成缩略图时会蒙上一层红色,实际使用中发现有部分图片会蒙上一层红色的蒙层,
因此通过Toolkit创建图片,然后转成BufferedImage的类型来解决这个问题。 */
Image imageToolkitTitle = Toolkit.getDefaultToolkit().createImage(url);
BufferedImage image = this.toBufferedImage(imageToolkitTitle);
...
/**
* 将图片转成BufferedImage格式
*
* @author SevenWong
* @date 2020-04-30 15:30:00
**/
private 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
Graphics2D g = bimage.createGraphics();
// 增加透明度解决png透明图片会变黑的问题
bimage = g.getDeviceConfiguration().createCompatibleImage(image.getWidth(null), image.getHeight(null), Transparency.TRANSLUCENT);
g = bimage.createGraphics();
// Paint the image onto the buffered image
g.drawImage(image, 0, 0, null);
g.dispose();
return bimage;
}