简体   繁体   中英

Drawing two overlayed images

I'm trying to draw 2 images, one on top of the other. The 1'st image is an arrow (that should appear like a header in the final image). The 1'st image (arrow) is 32x32 px while the 2'nd is 24x24.

Ideally I would like to draw the 2'nd image on top of the 1'st, starting from the right-bottom corner of the 1'st image.

Currently I'm using such code

// load source images
        BufferedImage baseImage = ImageIO.read(new File(baseImg.getFileLocation()));
        BufferedImage backgroundImage = ImageIO.read(new File(backgroundImg.getFileLocation()));

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

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

        int index = baseImg.getFileLocation().lastIndexOf(".png");
        String newFileName = baseImg.getFileLocation().substring(0, index);
        // Save as new image
        ImageIO.write(combined, "PNG", new File(newFileName + "_combined.png"));

but this won't quite work for me because the end result is a 32x32 image with the 2nd image being drawn only.

Any help is appreciated.

Thanks !

It looks like the issue here is you are drawing the 32x32 background image last, meaning it will be printed on top of the other image making it seem as if the 24x24 image was never drawn at all.

If you swap these two lines around, you should see both images. From:

g.drawImage(baseImage, 0, 0, null);
g.drawImage(backgroundImage, 0, 0, null);

to:

g.drawImage(backgroundImage, 0, 0, null);
g.drawImage(baseImage, 0, 0, null);


However this will draw the 24x24 image in the top-left corner, and you said you'd like it in the bottom-right. This can be done with some basic subtraction:

g.drawImage(baseImage, w - baseImage.getWidth(), h - baseImage.getHeight(), null);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM