简体   繁体   中英

Java change background color png image

I have been following some StackOverflow links using Graphics2D to change the background color of a BufferedImage.

The project I am working on requires that I read in a png image from a given url; the png image retrieved has a transparent background, and I would like to set it to white.

Here is what I have:

String u = this.format() ;
        BufferedImage image = null ;
        try{
            URL url = new URL(u) ;
            image = ImageIO.read(url) ;
            Graphics2D graphics = image.createGraphics() ;
            graphics.setBackground(Color.WHITE) ;
            graphics.clearRect(0, 0, image.getWidth(), image.getHeight()) ;


            ImageIO.write(image, "png", new File(outPath + fileName)) ;
            graphics.dispose() ;

        }
        catch(IOException e){
            e.printStackTrace() ;
        }

The problem I am running into is that when I view the image, the image appears as a solid white box. Apparently I have overlaid a white background on top of the existing image that I retrieved.

How can I preserve the original image and only change the background? Or set the background first and then overlay the retrieved image?

1- Load your image

image = ImageIO.read(url) ;

2- Create a new BufferedImage of the same size

BufferedImage background = new BufferedImage(image.getWidth(), image.getHeight, BufferedImage.TYPE_INT_RGB);

3- Fill the background image with the desired color

Graphics2D g2d = background.createGraphics();
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, background.getWidth(), background.getHeight());

4- Draw the original image onto the background...

g2d.drawImage(image, 0, 0, null);
g2d.dispose();

background is now filled with the desired color and has the image painted on top o it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM