Reputation: 639
I want my image, a buffered Image, to have a transparent background, I first tries using a png, then a gif, then I tried using imageFilters but I could also not hit it off, so now I decided to use a simple jpeg, set the background to a color and then get rid of that color, again, I assume imageFilters would fit for that, but I don't know exactly how to use them, the color I want to get rid of is 0xff00d8 (Magenta).
Can anyone help with a way to do this, or an example?
Upvotes: 0
Views: 175
Reputation: 639
I managed to fix it using JWindow, still, thank you Jason for all of your help
I have a translucentPane extending JPanel :
public TranslucentPane() {
setOpaque(false);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setComposite(AlphaComposite.SrcOver.derive(0.0f));
g2d.setColor(getBackground());
g2d.fillRect(0, 0, getWidth(), getHeight());
}
then I do this in my main UI :
robotUI roboUI = new robotUI();
roboUI.setBackground(new Color(0,0,0,0));
and my content pane is :
TranslucentPane pane = new TranslucentPane();
I hope this is enough for anyone to understand
Upvotes: 1
Reputation: 13986
jpeg
doesn't support transparency. Make sure your buffered image also supports transparency:
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
The A in TYPE_INT_ARGB
stands for alpha which is a measure of opacity.
You need to set the pixel value to 0x00000000 in order to make it transparent.
//Load the image
BufferedImage in = ImageIO.read(img);
int width = in.getWidth(), height = in.getHeight();
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bi.createGraphics();
g.drawImage(in, 0, 0, null);
g.dispose();
//Change the color
int colorToChange = 0xff00d8;
for (int x=0;x<width;x++)
for (int y=0;y<height;y++)
if(bi.getRGB(x,y)==colorToChange)
bi.setRGB(x,y,0x00FFFFFF&colorToChange);
bi.save(new File("out.png"));
Upvotes: 2