Java压缩图片错误——蒙上一层红色

1 起源

生产问题——现场运维反馈安卓客户端从文件服务器获取的压缩后的商品图片存在失真,属于偶现问题。

2 排查思路

(1)查看算法逻辑,没看出问题。

(2)百度,关键词:Java图片失真,看了很多博客都说是ImageIO和BufferedImage以及API参数的问题,比如加上参数 BufferedImage.SCALE_SMOOTH:

graph.drawImage(cropedImage.getScaledInstance(targetW,  targetH,  
BufferedImage.SCALE_SMOOTH), 0, 0, Color.white,null);

试过后,没有用,进一步查看JDK官方与图片相关的API,没有提到特别的注意事项。
(3)google、Stack Overflow
提到是JDK的bug,但是在oracle官网提到图片失真是JDK1.4的bug,但是1.6已结修复了,而项目中用到的是JDK1.7.
(4)百度,关键词:Java 压缩 图片后 表面变成红色
参考链接:https://blog.csdn.net/qq_25446311/article/details/79140008
根据文章内容,顺利解决。
转换代码:


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;
	}
	

3 总结

(1)搜索引擎使用
经过前后对比可以看到,准确描述问题的重要性。
(2)错误总结
只要使用 ImageIO.read 就可能存在图片蒙上红色的情况,原因是拍摄图片的设备问题,比如摄像机拍摄就可能存在该问题,手机可能就没有。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值