Copy two BufferedImages into one image side by side

Viewed 19490

I have two images and I'd like to copy these two images to a new image where the second image is beside the first image and not on top of it.

BufferedImage imgb1 = img1;
BufferedImage imgb2 = img2;
BufferedImage imgResult = new BufferedImage(...);

where imgResult contains the first and the second image next to each other.

2 Answers
public static BufferedImage joinBufferedImage(BufferedImage img1,
      BufferedImage img2) {
    //int offset = 2;
    int width = img1.getWidth();
    int height = img1.getHeight() + img2.getHeight();
    BufferedImage newImage = new BufferedImage(width, height,
        BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = newImage.createGraphics();
    Color oldColor = g2.getColor();
    g2.setPaint(Color.WHITE);
    g2.fillRect(0, 0, width, height);
    g2.setColor(oldColor);
    g2.drawImage(img1, null, 0, 0);
    g2.drawImage(img2, null, 0, img1.getHeight());
    g2.dispose();
    return newImage;
  }

Modified your code to print one image on top of eachother(as in one after another)

Related