Wednesday, September 28, 2011

How to merge multiple images into one image - Java ImageIO

My previous post shows how to split an image into chunks. Now let's see how to merge multiple images into one image. Say we need to concatenate following four image chunks. I got these chunks by splitting the image in the right hand side, using the image splitter.





















Following code shows how to concatenate the image chunks above into one image.

  1. int rows = 2; //we assume the no. of rows and cols are known and each chunk has equal width and height 
  2. int cols = 2; 
  3. int chunks = rows * cols; 

  4. int chunkWidth, chunkHeight; 
  5. int type; 
  6. //fetching image files 
  7. File[] imgFiles = new File[chunks]; 
  8. for (int i = 0; i < chunks; i++) { 
  9. imgFiles[i] = new File("archi" + i + ".jpg"); 

  10. //creating a bufferd image array from image files 
  11. BufferedImage[] buffImages = new BufferedImage[chunks]; 
  12. for (int i = 0; i < chunks; i++) { 
  13. buffImages[i] = ImageIO.read(imgFiles[i]); 
  14. type = buffImages[0].getType(); 
  15. chunkWidth = buffImages[0].getWidth(); 
  16. chunkHeight = buffImages[0].getHeight(); 

  17. //Initializing the final image 
  18. BufferedImage finalImg = new BufferedImage(chunkWidth*cols, chunkHeight*rows, type); 

  19. int num = 0; 
  20. for (int i = 0; i < rows; i++) { 
  21. for (int j = 0; j < cols; j++) { 
  22. finalImg.createGraphics().drawImage(buffImages[num], chunkWidth * j, chunkHeight * i, null); 
  23. num++; 
  24. System.out.println("Image concatenated....."); 
  25. ImageIO.write(finalImg, "jpeg", new File("finalImg.jpg")); 

No comments:

Post a Comment