前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java压缩图片错误——蒙上一层红色

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

作者头像
城市中的游牧民族
发布2019-02-21 10:15:59
1K0
发布2019-02-21 10:15:59
举报
文章被收录于专栏:前端真相前端真相

1 起源

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

2 排查思路

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

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

代码语言:javascript
复制
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 根据文章内容,顺利解决。 转换代码:

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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018年07月26日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1 起源
  • 2 排查思路
  • 3 总结
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档