java上傳png圖片出現紅色背景

java圖片上傳出現紅色背景

  • java圖片服務器上傳圖片都很正常,惟獨上傳png圖片時,png圖片變成紅色背景
緣由是讀取上傳數據時用的是ImageIO.read(inputstream)方法
public static BufferedImage getImages(byte[] data) throws IOException {  
        ByteArrayInputStream input = new ByteArrayInputStream(data);  
        return ImageIO.read(input);  
    }

解決辦法是:換成jdk中的Toolkit來讀取上傳的數據java

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

或:服務器

Image imageTookit = Toolkit.getDefaultToolkit().createImage(bytes);  
BufferedImage cutImage = toBufferedImage(imageTookit);

toBufferedImage():less

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;  
    }
相關文章
相關標籤/搜索