Java如何处理图片保存之后变红色的问题
更新时间:2023年11月18日 10:05:25 作者:请告诉他
这篇文章主要介绍了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());
具体如下

最终效果

总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
SpringBoot之ApplicationRunner解析(spring容器启动完成执行的类)
这篇文章主要介绍了SpringBoot之ApplicationRunner解析(spring容器启动完成执行的类),具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2023-05-05
SpringBoot整合MyBatis实现CRUD操作项目实践
本文主要介绍了SpringBoot整合MyBatis实现CRUD操作项目实践,如何实现数据库的CRUD创建、读取、更新、删除操作,具有一定的参考价值,感兴趣的可以了解一下2024-02-02
SpringCache缓存抽象之CacheManager与自定义键生成方式
本文将深入探讨Spring Cache的核心组件CacheManager及自定义键生成策略,帮助开发者掌握缓存配置与优化技巧,从而构建高效可靠的缓存系统,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教2025-04-04


最新评论