简体   繁体   中英

Transparent BufferedImage shows with a black background while painted on a JLabel

I've got a BufferedImage which is created from a png file. When creating it I set the type to be TYPE_INT_ARGB which should give me a transparent image. When I use paintComponent inside a JPanel to paint the image, I get the image with a black background. I really need to get it transparent so any help will be useful. Here is the code for clarity:

public class ImagePanel extends JPanel {      

    private static final long serialVersionUID = 1L;
    private BufferedImage image; 

    public ImagePanel() {
        this.image = null;
    }


    public void createImage(String fileName) {
        this.image = ImageUtilities.getBufferedImage(fileName, this);
        this.repaint();

     }

    public void paint(Graphics g) {
        g.drawImage(this.image, 0, 0, this);
    }
}

Here is how I load the image:

public class ImageUtilities {

/** Create Image from a file, then turn that into a BufferedImage.
*/

   public static BufferedImage getBufferedImage(String imageFile, Component c) {
       Image image = c.getToolkit().getImage(imageFile);
       waitForImage(image, c);
       BufferedImage bufferedImage = new BufferedImage(image.getWidth(c), image.getHeight(c),
                    BufferedImage.TYPE_INT_ARGB);
       Graphics2D g2d = bufferedImage.createGraphics();
       g2d.drawImage(image, 0, 0, c);
       return(bufferedImage);
   }

And one last thing to add is that this ImagePanel is inside another Panel, if that has any significance.

Not sure if this will solve your problem, but:

Are you restricted to using an older version of Java? Try using ImageIO.read(fileName) to load the image file.

Try this (ie setComposite()):

g2d.setComposite(AlphaComposite.SrcOver); g2d.setPaint(backgroundColor); g2d.fillRect(0, 0, w, h);

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