I want to know as simple as possible solution (so far I found only very complex solution) to simple question : How to draw an image in Graphics2D and set one color as fully transparent?
So far, I was trying something like this, but with no success :
private Image head;
public void draw(Graphics2D g) {
g.setComposite(AlphaComposite.Src);
Color transparentWhite = new Color(255,255,255,1);
g.drawImage(head, (int)posX, (int)posY, transparentWhite, null);
}
I have picture with white color around it which I do not want to draw.
Ok, finally found an answer, this is the most easies solution I have found.
private Image head;
//This is constructor, here I use method that adding transparency to image.
public Character(BufferedImage head){
this.head = makeColorTransparent(head, Color.WHITE);
}
public void draw(Graphics2D g) {
g.drawImage(head, (int) posX, (int) posY, null); //variable head is saved with transparency, so now it is drawing right
}
//Just copy-paste this method
public static Image makeColorTransparent(BufferedImage im, final Color color) {
ImageFilter filter = new RGBImageFilter() {
// the color we are looking for... Alpha bits are set to opaque
public int markerRGB = color.getRGB() | 0xFF000000;
public final int filterRGB(int x, int y, int rgb) {
if ((rgb | 0xFF000000) == markerRGB) {
// Mark the alpha bits as zero - transparent
return 0x00FFFFFF & rgb;
} else {
// nothing to do
return rgb;
}
}
};
ImageProducer ip = new FilteredImageSource(im.getSource(), filter);
return Toolkit.getDefaultToolkit().createImage(ip);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With