ImageIo.read读取图片有一层红色

使用BufferedImage headBuff = ImageIO.read(url);读取图片,读取后再重写有可能有一层红色。这就是ImageIO.read()方法读取图片时不能正确处理ICC信息的问题。
网上很多文章给出以下解决方案。

Image src = Toolkit.getDefaultToolkit().getImage(url);
BufferedImage originalImage = toBufferedImage(src);
public static 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;
}

这种方式在window系统上运行是没有问题的。但是部署到linux上运行时就会报错。

java.awt.HeadlessException: 
No X11 DISPLAY variable was set, but this program performed an operation which requires it.
        at sun.awt.HeadlessToolkit.getScreenSize(HeadlessToolkit.java:281)
        at ScreenCapture.main(ScreenCapture.java:23)

按照网上的方法:然后按照网上的方法,配置文件加 -Djava.awt.headless=true ClassName 但接着报异常。
因为使用Toolkit.getDefaultToolkit()需要图形窗口支持。这个就有点不太划算了。

于是使用ImageIcon读取图片,结果正常显示:

URL url = new URL(urlPath);
ImageIcon bufImg = new ImageIcon(url);
BufferedImage img = new BufferedImage(750, 1330, BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D) img.getGraphics();
g.drawImage(bufImg.getImage(), 45, 509, 660, 540, null);
g.dispose();

你可能感兴趣的:(java,ImageIO读取图片有红色,ImageIcon)