简体   繁体   English

透明BufferedImage在JLabel上绘制时显示黑色背景

[英]Transparent BufferedImage shows with a black background while painted on a JLabel

I've got a BufferedImage which is created from a png file. 我有一个从png文件创建的BufferedImage。 When creating it I set the type to be TYPE_INT_ARGB which should give me a transparent image. 在创建它时我将类型设置为TYPE_INT_ARGB,这应该给我一个透明的图像。 When I use paintComponent inside a JPanel to paint the image, I get the image with a black background. 当我在JPanel中使用paintComponent来绘制图像时,我得到的图像为黑色背景。 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. 最后要补充的是,如果有任何意义,这个ImagePanel就在另一个Panel中。

Not sure if this will solve your problem, but: 不确定这是否能解决您的问题,但是:

Are you restricted to using an older version of Java? 您是否仅限于使用旧版Java? Try using ImageIO.read(fileName) to load the image file. 尝试使用ImageIO.read(fileName)加载图像文件。

Try this (ie setComposite()): 试试这个(即setComposite()):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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