views:

485

answers:

3
+6  Q: 

Merging two images

Hello!

I need to merge two images (BufferedImage) in Java. It wouldn't be a problem if there was no transparency. The base image already has some transparency. I want to keep this as it is and apply a "mask" to it, the second image. This second image has no opaque pixels, in fact it's almost completely transparent, just has some less transparent pixels to give some sort of "light effect", like a reflex. Important detail: I don't want to do this on screen, with graphics, I need to obtain a BufferedImage with the resultant merge.

Can anyone help me? Thanks!

DETAILS: Merge two images maintaining transparency. This is what I need to do.

Note: this http://stackoverflow.com/questions/221830/set-bufferedimage-alpha-mask-in-java does not do what I need because it does not handle well with the two images having transparency - it modifies first picture transparency.

+2  A: 

I can't give you a specific answer, but java.awt.AlphaComposite here is your friend. You'll get absolute control over how you want the two images to merge. However it is not straightforward to use - you need to learn a bit of graphics theory first.

Steve McLeod
+2  A: 

Without knowing more about the effect you are trying to achieve, I'll just point out that you can also draw right onto a BufferedImage. So anything you could do on screen you can do right on the image itself.

So if all you want is one drawn on top of the other, that's really easy. Just grab the Graphics object for the base image and draw the other onto it.

Again, depending on the exact effect you are going for that may not work. More detail would allow better help. For example, is this a job for AlphaComposite as the other responder mentions or a custom ImageOp (or some combination of existing ImageOps).

PSpeed
+2  A: 

Just create a new BufferedImage with transparency, then paint the other two images (with full or semi-transparency) on it. This is how it will look like:

combining images

Sample code (images are called 'image.png' and 'overlay.png'):

File path = ... // base path of the images

// load source images
BufferedImage image = ImageIO.read(new File(path, "image.png"));
BufferedImage overlay = ImageIO.read(new File(path, "overlay.png"));

// create the new image, canvas size is the max. of both image sizes
int w = Math.max(image.getWidth(), overlay.getWidth());
int h = Math.max(image.getHeight(), overlay.getHeight());
BufferedImage combined = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);

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

// Save as new image
ImageIO.write(combined, "PNG", new File(path, "combined.png"));
Peter Walser
This seems to be EXACTLY what I need to do. I'll try it and get back to you!
GuilhermeA
... and it IS!! :) Thank you!
GuilhermeA