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 就可能存在图片蒙上红色的情况,原因是拍摄图片的设备问题,比如摄像机拍摄就可能存在该问题,手机可能就没有。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章