Transparent BufferedImage shows with a black background when it is written in JLabel

I have a BufferedImage that is created from a png file. When creating, I set the type to TYPE_INT_ARGB, which should give me a transparent image. When I use paintComponent inside a JPanel to paint an image, I get an image with a black background. I really need to make it transparent, so any help would be helpful. 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);
    }
}

This is how I upload 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 the last thing to add is that this ImagePanel is inside another panel, if that makes any difference.

+3
source share
3 answers

Not sure if this will solve your problem, but:

+3

Java? ImageIO.read(fileName) .

+2

Try this (i.e. setComposite ()):

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

0
source

Source: https://habr.com/ru/post/1778804/


All Articles