Wednesday, September 28, 2011

How to Split an Image into Chunks - Java ImageIO


Image splitting and concatenating and other image manipulation techniques are important in parallel computing. Say we are receiving small chunks of an Image which is being manipulated parallely. In such scenarios, we need to concatenate those chunks together and vice versa.

There is a pretty straight forward way to split an image using Java imageio package. Say you need to split following image into several chunks (you should decide the no. of rows and columns needed).















Now I am going to split this image into 16 chunks (4 rows and 4 columns). I have shown the code snippet below.
  1. import javax.imageio.ImageIO; 
  2. import java.awt.image.BufferedImage; 
  3. import java.io.*; 
  4. import java.awt.*; 

  5. public class ImageSplitTest { 
  6. public static void main(String[] args) throws IOException { 

  7. File file = new File("bear.jpg"); // I have bear.jpg in my working directory 
  8. FileInputStream fis = new FileInputStream(file); 
  9. BufferedImage image = ImageIO.read(fis); //reading the image file 

  10. int rows = 4; //You should decide the values for rows and cols variables 
  11. int cols = 4; 
  12. int chunks = rows * cols; 

  13. int chunkWidth = image.getWidth() / cols; // determines the chunk width and height 
  14. int chunkHeight = image.getHeight() / rows; 
  15. int count = 0; 
  16. BufferedImage imgs[] = new BufferedImage[chunks]; //Image array to hold image chunks 
  17. for (int x = 0; x < rows; x++) { 
  18. for (int y = 0; y < cols; y++) { 
  19. //Initialize the image array with image chunks 
  20. imgs[count] = new BufferedImage(chunkWidth, chunkHeight, image.getType()); 

  21. // draws the image chunk 
  22. Graphics2D gr = imgs[count++].createGraphics(); 
  23. gr.drawImage(image, 0, 0, chunkWidth, chunkHeight, chunkWidth * y, chunkHeight * x, chunkWidth * y + chunkWidth, chunkHeight * x + chunkHeight, null); 
  24. gr.dispose(); 
  25. System.out.println("Splitting done"); 

  26. //writing mini images into image files 
  27. for (int i = 0; i < imgs.length; i++) { 
  28. ImageIO.write(imgs[i], "jpg", new File("img" + i + ".jpg")); 
  29. System.out.println("Mini images created"); 
  30. } Parameter list of "drawImage()" (See line 28)
-- image - The source image
-- 0, 0 - X,Y coordinates of the 1st corner of destination image
-- chunkWidth, chunkHeight - X,Y coordinates of the opposite corner of destination image
-- chunkWidth * y, chunkHeight * x - X,Y coordinates of the 1st corner of source image block
-- chunkWidth * y + chunkWidth, chunkHeight * x + chunkHeight - X,Y coordinates of
the opposite corner of source image block

Now you'll see 16 image chunks formed in your working directory.

No comments:

Post a Comment