Way to change transparency with java swing.image

2019-08-25 19:52发布

问题:

I draw graphics in frame with this methods.

public void paint(Graphics g) {  
    screenImage = createImage(1280, 720); 
    screenGraphic = screenImage.getGraphics(); 
    screenDraw((Graphics2D) screenGraphic); 
    //g.drawImage(BG, 0, 0, null);
    g.drawImage(screenImage, 0, 0, null);
}

public void screenDraw(Graphics2D g) {
    g.drawImage(BG, 0, 0, null); 
    Graphics2D g2 = (Graphics2D)g;
    if(isMainScreen) {
        //g2.setComposite(alphaComposite);
        g2.drawImage(selectedImage, 100, 220, null);
    }
    paintComponents(g);
    this.repaint();  
}

I want to have selectedImage to be transparency 50% or other integer.

private Image selectedImage = new ImageIcon(Main.class.getResource("../pic/something.jpg")).getImage(); 

this is selectedImage, and it works well.

回答1:

Adapt a bit of Image -> BufferedImage code, and then you can set each pixel to be transparent

Image selectedImage = new ImageIcon([...]).getImage();

//Image -> BufferedImage code
BufferedImage img = new BufferedImage(selectedImage.getWidth(null), selectedImage.getHeight(null), BufferedImage.TYPE_INT_ARGB);
Graphics2D g = img.createGraphics();
g.drawImage(selectedImage, 0, 0, null);
g.dispose();

//set each pixel to be transparent
int transparency = 127; //0-255, 0 is invisible, 255 is opaque
int colorMask = 0x00FFFFFF; //AARRGGBB
int alphaShift = 24;
for(int y = 0; y < img.getHeight(); y++)
    for(int x = 0; x < img.getWidth(); x++)
        img.setRGB(x, y, (img.getRGB(x, y) & colorMask) | (transparency << alphaShift));

//img is now transparent, can replace selectedImage if you want (optional)
selectedImage = img;

If you use ImageIO.read(File) instead of ImageIcon.getImage(), it will give you a BufferedImage directly