Java上傳圖片時,對某些圖片進行縮放、裁剪或者生成縮略圖時會蒙上一層紅色,通過檢查只要通過ImageIO.read()方法讀取後再保存,該圖片便已經變成紅圖。所以,能夠推測直接緣由在於ImageIO.read()方法加載圖片的過程存在問題。java
[java] view plain copy 微信
public static BufferedImage getImages(byte[] data) throws IOException { less
ByteArrayInputStream input = new ByteArrayInputStream(data); ide
return ImageIO.read(input); ui
} url
通過查閱得知ImageIO.read()方法讀取圖片時可能存在不正確處理圖片ICC信息的問題,ICC爲JPEG圖片格式中的一種頭部信息,致使渲染圖片前景色時蒙上一層紅色。spa
再也不使用ImageIO.read()方法加載圖片,而使用JDK中提供的Image src=Toolkit.getDefaultToolkit().getImage.net
[java] view plain copy code
Image src=Toolkit.getDefaultToolkit().getImage(file.getPath()); orm
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;
}
參考: