java 红色_Java处理某些图片红色问题

百度了  微信平台上传图片变红  找到这个解决办法

问题现象:

Java上传图片时,对某些图片进行缩放、裁剪或者生成缩略图时会蒙上一层红色,经过检查只要经过ImageIO.read()方法读取后再保存,该图片便已经变成红图。因此,可以推测直接原因在于ImageIO.read()方法加载图片的过程存在问题。

publicstaticBufferedImage getImages(byte[] data)throwsIOException {

ByteArrayInputStream input = newByteArrayInputStream(data);

returnImageIO.read(input);

}

经过查阅得知ImageIO.read()方法读取图片时可能存在不正确处理图片ICC信息的问题,ICC为JPEG图片格式中的一种头部信息,导致渲染图片前景色时蒙上一层红色。

解决方案:

不再使用ImageIO.read()方法加载图片,而使用JDK中提供的Image src=Toolkit.getDefaultToolkit().getImage

Image src=Toolkit.getDefaultToolkit().getImage(file.getPath());

BufferedImage p_w_picpath=BufferedImageBuilder.toBufferedImage(src);//Image to BufferedImage

或者Toolkit.getDefaultToolkit().createImage

Image p_w_picpathTookit = Toolkit.getDefaultToolkit().createImage(bytes);

BufferedImage cutImage = BufferedImageBuilder.toBufferedImage(p_w_picpathTookit);

BufferedImageBuilder源码:

publicstaticBufferedImage toBufferedImage(Image p_w_picpath) {

if(p_w_picpathinstanceofBufferedImage) {

return(BufferedImage) p_w_picpath;

}

// This code ensures that all the pixels in the p_w_picpath are loaded

p_w_picpath = newImageIcon(p_w_picpath).getImage();

BufferedImage bp_w_picpath = null;

GraphicsEnvironment ge = GraphicsEnvironment

.getLocalGraphicsEnvironment();

try{

inttransparency = Transparency.OPAQUE;

GraphicsDevice gs = ge.getDefaultScreenDevice();

GraphicsConfiguration gc = gs.getDefaultConfiguration();

bp_w_picpath = gc.createCompatibleImage(p_w_picpath.getWidth(null),

p_w_picpath.getHeight(null), transparency);

} catch(HeadlessException e) {

// The system does not have a screen

}

if(bp_w_picpath ==null) {

// Create a buffered p_w_picpath using the default color model

inttype = BufferedImage.TYPE_INT_RGB;

bp_w_picpath = newBufferedImage(p_w_picpath.getWidth(null),

p_w_picpath.getHeight(null), type);

}

// Copy p_w_picpath to buffered p_w_picpath

Graphics g = bp_w_picpath.createGraphics();

// Paint the p_w_picpath onto the buffered p_w_picpath

g.drawImage(p_w_picpath, 0,0,null);

g.dispose();

returnbp_w_picpath;

}

参考:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值