BufferedImage rotated, change the resulting background

When I rotate the image with Graphics2D.rotate(), obviously, it leaves an empty spot in the corners. Empty corners become transparent.

I want my program to rotate BufferedImageand fill the remaining empty corners with white.

How can I do it?

In other words, I want to rotate the image while maintaining a white background for the entire image.

This is my function:

public BufferedImage rotateImage(BufferedImage image, double degreesAngle) {    
        int w = image.getWidth();    
        int h = image.getHeight();    
        BufferedImage result = new BufferedImage(w, h, image.getType());  
        Graphics2D g2 = result.createGraphics();  
        g2.rotate(Math.toRadians(degreesAngle), w/2, h/2);
        g2.drawImage(image,null,0,0);  
        return result;   
    }    

Then I use this image to draw it with a transparent JPanel, which I later add to JLayeredPane.

However, my image has transparent corners, and I want to fill them with white.

+2
source share
1 answer

( ) ...

...

BufferedImage, ...

public BufferedImage rotateImage(BufferedImage image, double degreesAngle) {    
    int w = image.getWidth();    
    int h = image.getHeight();    
    BufferedImage result = new BufferedImage(w, h, image.getType());  
    Graphics2D g2 = result.createGraphics();  
    g2.setColor(Color.WHITE);
    g2.fillRect(0, 0, w, h);
    g2.rotate(Math.toRadians(degreesAngle), w/2, h/2);
    g2.drawImage(image,null,0,0);  
    return result;   
}  

...

, ...

+3

All Articles