Alejandro Cabano Alejandro Cabano - 8 months ago 71
Java Question

overlay images in java

I hope you can give me some advices to solve my problem.
I need to overlay many images on a button.but the problem is,
this is the base image (tooth): (

my first image is this:
and then I put this:
the first image overlaps the second so I just can see only the second image...

maybe you will tell me that one option is change the order of the image before overlay, but the user will select what will be the first, maybe just want the first image, but in other cases user will put the first AND then the second or vice versa...

my code is this:

BufferedImage large=null;
large = File("firstimage.gif"));

BufferedImage small=null;

small = File("secondimage.gif"));

int w = Math.max(large.getWidth(), small.getWidth());
int h = Math.max(large.getHeight(), small.getHeight());

BufferedImage combined = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);

// paint both images, preserving the alpha channels
Graphics g = combined.getGraphics();
g.drawImage(large, 0, 0, null);
g.drawImage(small, 0, 0, null);

ImageIO.write(combined, "PNG", new File("twoInOne.png"));

ImageIcon icon1 = new ImageIcon(combined);

Maybe is a format of the images issue, or my code, but I prefer that you guys can help me with this problem thank you.

Now I uploaded the 3 images: I skip the base image (tooth) cause I dont think it will be the problem in there.


I need to edit my images to get transparent background?

To make a particular color transparent, you can iterate through the pixels of a BufferedImage or use a suitable LookupOp. For the latter, see the articles cited here. You can then combine the images using drawImage(). The default composite rule, AlphaComposite.SRC_OVER, should be satisfactory; if not, you can change it, as shown here.