Monday, August 10, 2009

Java: Concatenate multiple images into a single image

Let’s see how to concatenate (NOT combine) multiple images into a single image. So far I have tried with JPEGs and PNGs.
Here is the code:

public static void main(String[] args) throws IOException, Exception {
File file1 = new File("c:/BlackDragonWallpaper.jpg");
File file2 = new File("c:/black_attack_001_1024x768.jpg");
File file3 = new File("c:/windows-vista-wallpaper-120.jpg");
File file4 = new File("c:/wallpapers_windows_vista-xp-longnhor_-_redcode_0051.jpg");

BufferedImage img1 =;
BufferedImage img2 =;
BufferedImage img3 =;
BufferedImage img4 =;

int widthImg1 = img1.getWidth();
int heightImg1 = img1.getHeight();

int widthImg2 = img2.getWidth();
int heightImg2 = img2.getHeight();

BufferedImage img = new BufferedImage (
widthImg1 + widthImg2, // Final image will have width and height as
heightImg1 + heightImg2, // addition of widths and heights of the images we already have

boolean image1Drawn = img.createGraphics().drawImage(img1, 0, 0, null); // 0, 0 are the x and y positions

if(!image1Drawn) System.out.println("Problems drawing first image"); //where we are placing image1 in final image

boolean image2Drawn = img.createGraphics().drawImage(img2, widthImg1, 0, null); // here width is mentioned as width of

if(!image2Drawn) System.out.println("Problems drawing second image"); // image1 so both images will come in same level

boolean image3Drawn = img.createGraphics().drawImage(img3, 0, heightImg1, null);

if(!image3Drawn) System.out.println("Problems drawing third image");

boolean image4Drawn = img.createGraphics().drawImage(img4, widthImg1, heightImg1, null);

if(!image4Drawn) System.out.println("Problems drawing fourth image");

// horizontally
File final_image = new File("C:/Final.jpg");

boolean final_Image_drawing = ImageIO.write(img, "jpeg", final_image);

if(!final_Image_drawing) System.out.println("Problems drawing final image");


You can play with dimensions and the image placement positions and create final image with multiple images at different positions in it. You can put more images. I personally prefer “PNG” coz final image size will be smaller that what JPEG would have been and it is more clear.