Java如何处理图片保存之后变红色的问题
作者:请告诉他
这篇文章主要介绍了Java如何处理图片保存之后变红色的问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
问题
原图如下

上传之后效果如下

马赛克是我打的,别人家的logo,避免广告之嫌,系统审核不过
然而其他图片并不存在这个问题,如

这张,不存在这样的问题
两张图片不同点在于正常的为jpg,变色的为png
后面经过不同的尝试后发现,透明的PNG图、改alpha通道或四色图等都会引起以上问题
解决办法
有两种,这里分享比较好用的一种,方便快捷,复制粘贴就能用
// 这里是直接根据url读取图片
public static BufferedImage getBufferedImage(String imgUrl) throws MalformedURLException {
URL url = new URL(imgUrl);
ImageIcon icon = new ImageIcon(url);
Image image = icon.getImage();
// 如果是从本地加载,就用这种方式,没亲自测试过
// Image src=Toolkit.getDefaultToolkit().getImage(filePath);
// This code ensures that all the pixels in the image are loaded
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;
}我的是在原代码中,将
bi = ImageIO.read(inStream);
替换为
bi = getBufferedImage(inFile.getPath());
具体如下

最终效果

总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
