jeet
jeet

Reputation: 795

Java: Merging 2 images is not working

I'm trying to read 2 image files, then merge image2 on top of image1, but the code below does not seem to work. After saving, I only see image1 as original. Both images are PNG.

String url= uploadPath + filename;
BufferedImage im = ImageIO.read(url);
String url2= "image2.png";
BufferedImage im2 = ImageIO.read(url);
Graphics2D g = im.createGraphics();
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.8f));
g.drawImage(im2, im.getWidth()/2, im.getHeight()/2, null);
g.dispose();
ImageIO.write(im, "png", new File( url ));

What did I miss here? Thanks

Upvotes: 0

Views: 923

Answers (3)

Audrius Meškauskas
Audrius Meškauskas

Reputation: 21728

You can also try SRC_ATOP with the transparency 0.5.

Upvotes: 1

MadProgrammer
MadProgrammer

Reputation: 347184

I had no issues getting it to work.

enter image description here

I did find this line...

g.drawImage(im2, im.getWidth()/2, im.getHeight()/2, null);

Of a little concern. It MIGHT be possible to render the image outside of the background image, if the image sizes are just right. You should be using coordinates that are relative to the master image...

public class MergeImages {

    public static void main(String[] args) {
        File inner = new File("Inner.png");
        File outter = new File("Outter.png");

        try {

            BufferedImage biInner = ImageIO.read(inner);
            BufferedImage biOutter = ImageIO.read(outter);

            System.out.println(biInner);
            System.out.println(biOutter);

            Graphics2D g = biOutter.createGraphics();
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.8f));
            int x = (biOutter.getWidth() - biInner.getWidth()) / 2;
            int y = (biOutter.getHeight() - biInner.getHeight()) / 2;
            System.out.println(x + "x" + y);
            g.drawImage(biInner, x, y, null);
            g.dispose();

            ImageIO.write(biOutter, "PNG", new File("Outter.png"));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

I'd also double check shuangwhywhy suggestion of making sure you not reading in the same file twice ... I did that some thing when testing the code :P

Upvotes: 3

shuangwhywhy
shuangwhywhy

Reputation: 5625

Your problem is im2 is exactly the same as im:

BufferedImage im = ImageIO.read(url);
BufferedImage im2 = ImageIO.read(url);

I guess it is a typo: it should be url2 rather than url to be read as im2, Am I right?

BufferedImage im2 = ImageIO.read(url2);

Upvotes: 3

Related Questions