Java处理某些图片红色问题
百度了 ?微信平臺(tái)上傳圖片變紅 ?找到這個(gè)解決辦法
問(wèn)題現(xiàn)象:
Java上傳圖片時(shí),對(duì)某些圖片進(jìn)行縮放、裁剪或者生成縮略圖時(shí)會(huì)蒙上一層紅色,經(jīng)過(guò)檢查只要經(jīng)過(guò)ImageIO.read()方法讀取后再保存,該圖片便已經(jīng)變成紅圖。因此,可以推測(cè)直接原因在于ImageIO.read()方法加載圖片的過(guò)程存在問(wèn)題。
[java]?view plain?copy?
public?static?BufferedImage?getImages(byte[]?data)?throws?IOException?{??
????????ByteArrayInputStream?input?=?new?ByteArrayInputStream(data);??
????????return?ImageIO.read(input);??
????}??
經(jīng)過(guò)查閱得知ImageIO.read()方法讀取圖片時(shí)可能存在不正確處理圖片ICC信息的問(wèn)題,ICC為JPEG圖片格式中的一種頭部信息,導(dǎo)致渲染圖片前景色時(shí)蒙上一層紅色。
解決方案:
不再使用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
轉(zhuǎn)載于:https://blog.51cto.com/guowang327/1866166
總結(jié)
以上是生活随笔為你收集整理的Java处理某些图片红色问题的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: jsp页面textarea中换行替换问题
- 下一篇: Java 异常处理