tags:

views:

105

answers:

1

Hi,

I have two ImageIcons and I want to create a third ImageIcon which has nr 2 drawn upon nr 1. How would I best do that?

+7  A: 

The following code takes an Image from two ImageIcons and creates a new ImageIcon.

The image from the second ImageIcon is drawn on top of the image from the first, then the resulting image is used to make a new ImageIcon:

Image img1 = imageIcon1.getImage();
Image img2 = imageIcon2.getImage();

BufferedImage resultImage = new BufferedImage(
    img1.getWidth(null), img1.getHeight(null), BufferedImage.TYPE_INT_ARGB);

Graphics2D g = resultImage.createGraphics();
g.drawImage(img1, 0, 0, null);
g.drawImage(img2, 0, 0, null);
g.dispose();

ImageIcon resultImageIcon = new ImageIcon(resultImage);

Edit (Fixed some errors, added transparency support.)

For allowing transparency, the BufferedImage.TYPE_INT_ARGB can be used for the image type in the constructor, rather than BufferedImage.TYPE_INT_RGB which does not have an alpha channel.

coobird
That is pretty close, the new image seems to have a black background instead of a transparent one
willcodejavaforfood
Changed the type to TYPE_4BYTE_ABGR and that took care of the alpha. Many thanks
willcodejavaforfood