美文网首页
java使用Graphics合成图片时出现变红的问题解决方法

java使用Graphics合成图片时出现变红的问题解决方法

作者: 今汐猎人 | 来源:发表于2018-02-08 19:03 被阅读0次

    在做合成图片的时候偶尔遇到某些图片原图是这样的


    QQ图片1.jpg

    合成后 图片是这样的


    QQ图片.png

    表面被涂上了一层红色
    网上查阅资料后知道 ImageIO.read(url)方法有问题 读取图片的时候可能会不正确处理ICC ,ICC为JPEG图片格式中的一种头部信息。

    解决方案

            Image src=Toolkit.getDefaultToolkit().getImage(file.getPath());  
            BufferedImage image=BufferedImageBuilder.toBufferedImage(src);//Image to BufferedImage 
    

    BufferedImageBuilder 源码

    public class BufferedImageBuilder{
        
        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;  
        }
        
        
        
    }
    

    相关文章

      网友评论

          本文标题:java使用Graphics合成图片时出现变红的问题解决方法

          本文链接:https://www.haomeiwen.com/subject/nnaozxtx.html