Java处理某些图片红色问题
百度了 ?微信平臺上傳圖片變紅 ?找到這個解決辦法
問題現象:
Java上傳圖片時,對某些圖片進行縮放、裁剪或者生成縮略圖時會蒙上一層紅色,經過檢查只要經過ImageIO.read()方法讀取后再保存,該圖片便已經變成紅圖。因此,可以推測直接原因在于ImageIO.read()方法加載圖片的過程存在問題。
[java]?view plain?copy?
public?static?BufferedImage?getImages(byte[]?data)?throws?IOException?{??
????????ByteArrayInputStream?input?=?new?ByteArrayInputStream(data);??
????????return?ImageIO.read(input);??
????}??
經過查閱得知ImageIO.read()方法讀取圖片時可能存在不正確處理圖片ICC信息的問題,ICC為JPEG圖片格式中的一種頭部信息,導致渲染圖片前景色時蒙上一層紅色。
解決方案:
不再使用ImageIO.read()方法加載圖片,而使用JDK中提供的Image src=Toolkit.getDefaultToolkit().getImage
[java]?view plain?copy?
Image?src=Toolkit.getDefaultToolkit().getImage(file.getPath());??
BufferedImage?p_w_picpath=BufferedImageBuilder.toBufferedImage(src);//Image?to?BufferedImage??
或者Toolkit.getDefaultToolkit().createImage
[java]?view plain?copy?
Image?p_w_picpathTookit?=?Toolkit.getDefaultToolkit().createImage(bytes);??
BufferedImage?cutImage?=?BufferedImageBuilder.toBufferedImage(p_w_picpathTookit);??
BufferedImageBuilder源碼:
[java]?view plain?copy?
public?static?BufferedImage?toBufferedImage(Image?p_w_picpath)?{??
????????if?(p_w_picpath?instanceof?BufferedImage)?{??
????????????return?(BufferedImage)?p_w_picpath;??
????????}??
????????//?This?code?ensures?that?all?the?pixels?in?the?p_w_picpath?are?loaded??
????????p_w_picpath?=?new?ImageIcon(p_w_picpath).getImage();??
????????BufferedImage?bp_w_picpath?=?null;??
????????GraphicsEnvironment?ge?=?GraphicsEnvironment??
????????????????.getLocalGraphicsEnvironment();??
????????try?{??
????????????int?transparency?=?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??
????????????int?type?=?BufferedImage.TYPE_INT_RGB;??
????????????bp_w_picpath?=?new?BufferedImage(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();??
????????return?bp_w_picpath;??
????} ?
參考:
http://blog.csdn.net/kobejayandy/article/details/44346809
轉載于:https://blog.51cto.com/guowang327/1866166
總結
以上是生活随笔為你收集整理的Java处理某些图片红色问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: jsp页面textarea中换行替换问题
- 下一篇: Java 异常处理