Wednesday, February 24, 2010

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.

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.awt.*;

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

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

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

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

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

        //writing mini images into image files
        for (int i = 0; i < imgs.length; i++) {
            ImageIO.write(imgs[i], "jpg", new File("img" + i + ".jpg"));
        }
        System.out.println("Mini images created");
    }
}

 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.


60 comments:

Aditya Ch said...

Great to see this post. Really good information. As I see, it's in AWT context.
Post on Base64 encoding of any image and sending it across the wire would be of great help. Can you please do that, if you have related information with you ?

Lucas Schirm said...

Great Tip! i`m try and work`s fine, thank u!

nicolas said...

Thanks so much! You're a life saver!

sahil chug said...

Awesome Post man!!

vicky ceg said...

hey sis i need a help
please give ur mail id :)
cant send msg to your facebook profile !!

Unknown said...

now i am doing my final year project in image security in which we have to split the image into parts so that no one cannot save the image by right clicking on it and select the save as option.the entire image should not be saved,only the part of the image where we clicked should be saved.. can you pls help me out???

kalani Ruwanpathirana said...

@Unknown: well, I think you can split the image into tiny parts (as shown in this post) and then display those parts without re-merging them (that might be some nice html work - as user gets the illusion that he is looking at a non splitted image)

nikhil.. said...

Nice post, thank you

sudha said...

Hi mam,i need to split an image into OVERLAPPING blocks..the code provided here is for non-overlapping blocks..could you pls help me for my final yr project..thank u :):)

priyanka misal said...

now ,i am dividing the image into 16*16 blocks. And want to display all chunks.Can you please help me.

priyanka misal said...

i have didided the image into 16*16 blocks.now i want to dispaly all blocks with small spacing.please can u do this in java?

Androidcrazy said...

Can you please tell me how i will place the chunks like image2 in third row and image10 in first row

thanks

Anu said...

do u knw the java codes to split a video into frames.........??plz reply.

kalani Ruwanpathirana said...

@ sudha : I think what you need is to play with drawImage() method. It would be good to try out different method to give the arguments to that method (ex. chunkwidth*x-5 etc..). It will decide the splitting coordinates of the image. You just need to give the coordinates appropriately. Sorry, I didn't try this out but I think it would work.

kalani Ruwanpathirana said...

@ priyanka : Yes, I think it is possible. Please have a look at this merge image post. You just have alter that code to add spacing there.

kalani Ruwanpathirana said...

@ Androidcrazy : Sorry, I think I didn't get your question. This code does image splitting and what I have shown is the image thumbnails in the folder. Please let me know if you need more info.

@ Anu : Sorry Anu, I am not aware of image splitting.

Matthews said...

pls help me eith java code to code a module that split and image into clippings and merge them back, it also calculate the compered match in percentage.

Matthews said...

codes to Construct the face of criminal by clubbing all freezed clippings and match clips

Matthews said...

Um developing a system tht identify criminal face, Titled 'Criminal face identification system' pls help me code the 'Splitting and Merging Module!
Splitting:View all clips and select the clip shown by eyewitness
Construction:Construct the face of criminal by clubbing all freezed clippings.
Pls reply via: yashiindi@gmail.com
or here altenatively

Anki said...

hi.i used the codes in your to split and combine a 256x256 image.however, the final image differs from the original when compared pixel by pixel.The tint of the image is getting affected.please help asap.i need it for my project

Jacul said...

Bravo! Good job! Thank you man! You help me a lot!

harshal chaudhari said...

please help me out for the java code for dividing the image into pixels.

Đôn Nguyễn said...

Very helpful! ;)

aaaa said...
This comment has been removed by the author.
aaaa said...

thank you so much for this code and keep it up

aaaa said...

thank you so much for this code and keep it up

Pankaj Jakate said...

awesome program great work

Pankaj Jakate said...

great....

Maarten said...

exactly what i needed :)
thanks a lot!

sumi said...

i am not able to run this program. i am compiling this program successfully but at the run time i have found java.io.filenotfoundexception
plz help me
thank you

proskier said...
This comment has been removed by the author.
proskier said...
This comment has been removed by the author.
darshni dubba said...

Thanx a lot.................

Rajib Hossain said...

Thank you for sharing, you keep your word, that's sweet
Split face Tile

Sumit Jain said...

Thanks mam.... It is helpful to me... Could you please help me.... I want to split the video file in frames in core java... Could you please help me???

Bình Đàm said...

thanks you, but when i create image done then it show only black

Bình Đàm said...

help me !!!! thank so much!

BINH DQ said...

create image successfully ,thanks so much.
i forget to take
image.getWidth/row
image.getHeight/col
should lead to error

AIM said...

Kalany, can the split part of the code works in android?

vennela chowdary said...

Hey i am able to generate mini images using your code. But i can see only black images. My image width and height are 259 and 154.

vennela chowdary said...

Hey sorry kalani, i forgot to divide my chunkHeight/Width with rows/ cols resp..Thanks for the post!

Gowtham Agraharam said...

Hi,

I need to split a particular part of image into chunks.I tried some combinations it didn't work.Can u please help me regarding this issue.

regards
Gowtham

website design said...

What a good job for this post. Very rich and constructive at the same time. I want to say a thumbs up to the creator for keeping this web site simple. Congratulations finally a web site of top-level.
website design

Tukaram Ghule said...

I want to split image in 20 parts. After splitting an image it should looks like an original image. I want co-ordinate of particular part when i click on it. If I click anywhere on particular part of image then it should show same co-ordinate, means 1 co-ordinate for 1 part and so on.

Is it possible to do this?
Can u help me regarding this ?
Do reply please.........

Hema Aswani said...

How to create a new image from existing image from known co-ordinates?

karthik kiccha said...

thank you very much..

Pooja Garg said...

how to divide this image into 9 blocks

Add pk said...

What will happen if I applied this code to divide images of different resolutions and store them in matrix.Will this matrices are of different size for each image?
Plz Reply soon.....

junaid raza said...

My code is not running..
(The system cannot find the file specified) Error is shown..
I have alreday try for URL method for image..No output

junaid raza said...

Everthing is done..
But images are not generated.The file path srror rmoved when i put the address from my file system.
Now my mini images are not saved.

Ayyanar Raja said...

thanks ..sir

Freethinker said...

Hi Kalani, that was nice real piece of code.

Vishnu Kr said...

its an awesome code for slicing images so i really want to appreciate you.

but its didn't work for me :-(. I tried to slice the image by its own width and height (rows=width; and cols = height, the image resolution is 600x700). so i got "java.lang.OutOfMemoryError: Java heap space". because creating objects of BufferedImage inside the loop.

So could you please suggest an another option to slice the high resolution images into tiles?.

Poornima Dhadekar said...

how to assign serial numbers to image chunks to use it as password

Ruveyda Kuş said...

Hi!
I want to write that code,for example tiger image, Tiger image is split into 10x10 blocks and sorted by intensities. How can i calculate intensities?
Can you help me?

Tommy said...

This is EXACTLY what I've been looking for, thanks for posting :)

Neeraj Tehra said...

Hey can we divide the images based on the co-ordinates after clicking on the part of the image like i have nespaper and on clicking on a article only that article should be popped up.
Thanks in advance.

Anonymous Snowboarder said...

Is there a reason not to use getSubimage(x,y,chunkW,chunkH)?

Ilayaraj Ramasamy said...

Found what i hav been looking for
Tq

Debjit Ghosh said...

Hi, your blog is very good and it works perfectly to save split images. However, I am trying to print each small image rather than to save the images. But the problem is that the print quality is very poor. Is there any code to print a good quality of small image?

Related Posts with Thumbnails