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.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 =; //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);
        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.


Unknown 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!

Unknown 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 !!

sowmya 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)

Anonymous 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 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


Unknown 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:
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!

Unknown said...

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

Unknown 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

Unknown said...

awesome program great work

Unknown said...


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
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.
Unknown said...

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

Unknown 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???

Unknown said...

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

Unknown said...

help me !!!! thank so much!

Unknown said...

create image successfully ,thanks so much.
i forget to take
should lead to error

AIM said...

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

Unknown 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.

Unknown said...

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

Gowtham Agraharam said...


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.


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 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.........

Unknown said...

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

Unknown said...

thank you very much..

Unknown said...

how to divide this image into 9 blocks

Unknown 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.....

Unknown 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

Unknown 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.

Unknown said...

thanks ..sir

Freethinker said...

Hi Kalani, that was nice real piece of code.

Unknown 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?.

Unknown said...

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

Unknown said...

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)?

Unknown said...

Found what i hav been looking for

Unknown 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?

Unknown said...

Checkout my video on it

Unknown said...
This comment has been removed by the author.
Pawel Co Faddey said...

Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java Online Training in India . Nowadays Java has tons of job opportunities on various vertical industry.

Adrian said...

If you are looking to divide an image into overlapping blocks, this site might help you understand a little bit.

siva said...

This is an awesome post.Really very informative and creative contents. These concept is a good way to enhance the knowledge.
I like it and help me to development very well.Thank you for this brief explanation and very nice information.Well, got a good knowledge.
Java training in Indira nagar
Java training in Rajaji nagar
Java training in Marathahalli
Java training in Btm layout
Java training in Marathahalli

digitalsourabh said...

Best PHP Training Institute in Bhopal
Graphic designing training in bhopal
Python Coaching in Bhopal
Android Coaching in Bhopal
Machine Learning Course in Bhopal
Digital Marketing Training in Bhopal
IoT Training in Bhopal
Artificial Intelligence Training in Bhopal

Techxinx said...

I am a regular reader of your blog and I find it really informative. for more info contact us
CPCT Coaching in Bhopal
java coaching in bhopal
Autocad classes in bhopal
Catia coaching in bhopal

michaelwaung said...

so useful blog !

nadiya said...

Thanks for updating this information. Good job.
German Classes in Chennai
German Language Classes in Chennai
French Classes in Chennai
pearson vue test center in chennai
Informatica Training in Chennai
Data Analytics Courses in Chennai
German Classes in T Nagar
German Classes in Anna Nagar

shivam said...

Flying Shift - Packers & Movers in Bhopal

Newagedigitech said...

Whatsapp Marketing
Whatsapp Marketing for business

Riya Raj said...

Phenomenal Blog!!! thanks for your post and awaiting for your new updates...
Digital Marketing Course in Chennai
Digital Marketing Training in Chennai
best digital marketing course in chennai
Digital Marketing Course
Digital marketing course in Thiruvanmiyur
Digital marketing course in Velachery
Python Training in Chennai
Software testing training in chennai
Python Training in Chennai
JAVA Training in Chennai

Unknown said...

how to we run those code for splitting amd merge image?

Rajesh said...

Nice information, want to know about Selenium Training In Chennai
Selenium Training In Chennai
Data Science Course In Chennai
Protractor Training in Chennai
jmeter training in chennai
Rpa Training Chennai
Rpa Course Chennai
Selenium Training institute In Chennai
Python Training In Chennai

Rajesh said...

Rpa Training in Chennai
Rpa Course in Chennai
Blue prism training in Chennai

Rajesh said...

Data Science Training In Chennai
Data Science Course In Chennai
Data Science Course In Chennai

shivam said...

Top engineering colleges in India

technical news

digital marketing course in bhopal

what is microwave engineering
how to crack filmora 9
what is pn junction

jasmin said...

9apps Text Now
9apps Calender
9apps Google
9apps Google Earth
9apps Media Player
9apps Video Editor
9apps Google Services
9apps Gboard
9apps Abode
9apps Likee

Geraldine Garcia said...

WP Engine has fantastic offers for this Black Friday Hosting Deals Cyber Monday just like every other year. WP Engine offers five months of free hosting when signed up for annual shared plans. You need to use the coupon code cybrwknd30 From Thursday, November 28 – December 2, 2019, to avail of these deals as I also need to remind you, the deal will be applicable only for new users and not for existing users upgrades.

Customer relationship management said...

Its really helpful for the users of this site. I am also searching about these type of sites now a days. So your site really helps me for searching the new and great stuff.

sap s4 hana training in bangalore

sap simplefinance training in bangalore

sap training in bangalore

sap abap training in bangalore

sap basis training in bangalore

sap bi training in bangalore

sap dynpro training in bangalore

sap fico training in bangalore

Customer relationship management said...

This is the exact information I am been searching for, Thanks for sharing the required infos with the clear update and required points. To appreciate this I like to share some useful information.

sap crm training in bangalore

sap ehs training in bangalore

sap bw training in bangalore

sap hana training in bangalore

sap hr training in bangalore

sap mm training in bangalore

sap pm training in bangalore

sap pp training in bangalore

Customer relationship management said...

It is very good and useful for students and developer.Learned a lot of new things from your post Good creation,thanks for give a good information.

sap ps training in bangalore

sap qm training in bangalore

sap scm training in bangalore

sap sd training in bangalore

sap srm training in bangalore

sap hybris training in bangalore

sap wm training in bangalore

sap ewm training in bangalore

Customer relationship management said...

I have to voice my passion for your kindness giving support to those people that should have guidance on this important matter.

sap solution manager training in bangalore

sap security training in bangalore

sap grc security training in bangalore

sap ui5 training in bangalore

sap bods training in bangalore

sap apo training in bangalore

sap gts training in bangalore

sap hana admin training in bangalore

Customer relationship management said...

Excellent post for the people who really need information for this technology.

sap idm training in bangalore

sap mdm training in bangalore

sap successfactor training in bangalore

sap fiori training in bangalore

sap bpc training in bangalore

sap testing training in bangalore

sap testing training in bangalore

sap simple logistics training in bangalore

python training in vijayawada said...

We as a team of real-time industrial experience with a lot of knowledge in developing applications in python programming (7+ years) will ensure that we will deliver our best in python training in vijayawada. , and we believe that no one matches us in this context.

Johan said...

Thanks for sharing amazing information.Gain the knowledge and hands-on experience.

java training in bangalore

java courses in bangalore

java classes in bangalore

java training institute in bangalore

java course syllabus

best java training

java training centers

Johan said...

This is most informative and also this post most user friendly and super navigation to all posts. Thank you so much for giving this information to me.

digital marketing training in bangalore

digital marketing courses in bangalore

digital marketing classes in bangalore

digital marketing training institute in bangalore

digital marketing course syllabus

best digital marketing training

digital marketing training centers

Johan said...

Thanks for sharing amazing information.Gain the knowledge and hands-on experience.

java training in bangalore

java courses in bangalore

java classes in bangalore

java training institute in bangalore

java course syllabus

best java training

java training centers

aj said...
This comment has been removed by the author.
Shopclues Winner List said...

Shopclues winner list here came up with a list of offers where you can win special shopclues prize list by just playing a game & win prizes.
Shopclues lucky customer
Shopclues lucky customer 2020
Winner list Shopclues
Shopclues Prize
Prize Shopclues

GlobalEmployees said...

Find my blog post here
web design

hami said...

click here for more info.

Shopclues Winner List said...

Shopclues winner list here an offer you can win the Shopclues lucky draw. Here you can win the Shopclues winner list 2020 and Shopclues winner list. Shopclues lucky draw where you can win the prize just playing the game. You can also check Shopclues lucky draw and Shopclues winner name 2020.

ExcelR Digital Marketing Courses In Bangalore said...

Companies turn to the Internet to generate sales, the need for experts in digital marketing has never been greater.
ExcelR Digital Marketing Courses In Bangalore

svrtechnologies said...

Pretty article! I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing.

automated software testing training

Jack sparrow said...

Pretty article! I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision. i also want to share some infor mation regarding sap pp tutorial and sap sd training .keep sharing.

kalavani said...

The blog you shared is very good. I expect more information from you like this blog. Thankyou.
Python Training in bangalore
Python Course in Bangalore
Angularjs course Bangalore
Angularjs Training in Bangalore
Web Designing Course in bangalore
Web Development courses in bangalore
Salesforce Course in Bangalore
salesforce training in bangalore
Big Data Training in Bangalore
Hadoop Training in Bangalore

Excelrsolutions said...

I just got to this amazing site not long ago. I was actually captured with the piece of resources you have got here. Big thumbs up for making such wonderful blog page!. bangalore digital marketing course

dataexpert said...

Very nice job... Thanks for sharing this amazing and educative blog post! Digital Marketing Course Pune

Shivani said...

Way cool! Some very valid points! I appreciate you penning this article and also the rest of the site is really good.

Advanced Java Training Center In Bangalore

selenium training in Bangalore

Selenium Courses in Bangalore

best selenium training institute in Bangalore

selenium training institute in Bangalore


svrtechnologies said...

I am inspired with your post writing style & how continuously you describe this topic. After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic.

sapui5 tutorial

gadgetsdora said...

Greetings, I think your blog may be having browser compatibility issues. When I take a look at your web site in Safari, it looks fine however, if opening in I.E., it has some overlapping issues. I simply wanted to provide you with a quick heads up! Besides that, fantastic website!

Unknown said...

I can see that you are an expert at your field! I am launching a website soon, and your information will be very useful for me.. Thanks for all your help and wishing you all the success in your business.satta king

svrtechnologies said...

I am inspired with your post writing style & how continuously you describe this topic. After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic...

workflow in sap abap

kimi jhaveri said...

Hi, your article was of great help. I loved the way you shared the information, thanks.
Amazing article, I highly appreciate your efforts, it was highly helpful. Thank you CEH Training ,CEH Certification, CEH Online Course, Ethicalhacking

sachin nagar said...

Hi, This is a great article. Loved your efforts on it buddy. Thanks for sharing this with us.
Get cissp
it training courses.
CISSP training ,cissp exam cost, CISSP certification. .Get VMware, vmware training, vmware course, vmware online training., vmware interview questions and answers, vmware Certification, AWS, aws training, aws course, aws certification training, aws online training
Get PMP pmp certification, pmp training, pmp certification in gurgaon,pmp certification cost, pmp training certification

sachin nagar said...

Hi this is the nice blog, thanks for sharing us
Get Azure, azure training,azure certification,microsoft azure training,azure course,azure online training

Pyramidions said...

It is one of the value added site I have visited. Good information given to readers.

Mobile App Development Companies in Chennai

Ravi said...

thanks for valuable information.

sachin nagar said...

Hi, This is your awesome article , I appreciate your effort, thanks for sharing us.
cism training
cism certification

cisa training,
cisa certification
cisa exam

ek said...

This is a splendid website! I"m extremely content with the remarks!.
ExcelR Solutions

Mr Rahman said...

Really Great Post & Thanks for sharing.

Oflox Is The Best Website Designing Company In Dehradun

Ahsan said...

i often do this practice for Mobile Mall Pakistan

Ranvijay Singh said...

SEO Training in Bhopal
Digital Marketing Training in Bhopal
SEO Company in Bhopal
Digital Marketing Company in Bhopal
High PR Profile Creation Sites
Web 2.0 Sites list
Directory Submission Sites list
Article Submission Sites list
Social Bookmarking Sites list
Digital Marketing Course in Bhopal

Rajesh said...

It is actually a great and helpful piece of information about Java. I am satisfied that you simply shared this helpful information with us. Please stay us informed like this. Thanks for sharing.
Java training in chennai | Java training in annanagar | Java training in omr | Java training in porur | Java training in tambaram | Java training in velachery

AK said...

Informative post, i love reading such posts. Read my posts here

latchu kannan said...

Thanks for your valuable content.
AngularJS training in chennai | AngularJS training in anna nagar | AngularJS training in omr | AngularJS training in porur | AngularJS training in tambaram | AngularJS training in velachery

saran said...

nice post
Digital Marketing Training Course in Chennai | Digital Marketing Training Course in Anna Nagar | Digital Marketing Training Course in OMR | Digital Marketing Training Course in Porur | Digital Marketing Training Course in Tambaram | Digital Marketing Training Course in Velachery

Related Posts with Thumbnails