ImageIcon + ImageIcon = ImageIcon

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

+1


a source to share


1 answer


The following code takes Image

the two ImageIcon

and creates a new one ImageIcon

.

The image from the second ImageIcon

is drawn over the image from the first, then the resulting image is used to create a new one 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 bugs, added transparency support.)

For transparency, BufferedImage.TYPE_INT_ARGB

can be used for an image type in the constructor, rather than BufferedImage.TYPE_INT_RGB

one that does not have an alpha channel.

+7


a source







All Articles