Saturday, February 27, 2010

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.
int rows = 2;   //we assume the no. of rows and cols are known and each chunk has equal width and height
        int cols = 2;
        int chunks = rows * cols;

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

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

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

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

62 comments:

HazyMind said...

This was very helpful. Thank you!

Unknown said...

hey...thankx a lot...ws helpful 4 our prjct...

Ardisan said...

Thankx Kalani, this was very helpful for may final project, since I was to start my project using java.

kalani Ruwanpathirana said...

welcome...you all.

Knick said...

On line 23: shouldn't it be "chunkWidth*cols" instead of "chunkWidth*chunks" (respectively "rows")? Or not?

Anyway thanks a lot!

kalani Ruwanpathirana said...

Thanks Knick for pointing that out. (I couldn't test this code but I'll change that)

Avalon-Zone said...

Hi,

I gonna use your piece of code but I'm not sure about memory consumption because I would like to use it to merge a large amount of image... about 4000 images with a maximum size of 256x256x8bit / image. I'm not sure that Java will be able to handle that. Do you have any advice concerning my case ?

Thanks

krish indhu said...

hi...i need the java code for replacing some parts in image...i tried many times.but i cannot get any code for image parts replacing,i completed half of the project,if i got the java code for image parts replacing,i completed my project...plzzz plzzz help me

krish indhu said...

hi...i need the java code for replacing some parts in image...i tried many times.but i cannot get any code for image parts replacing,i completed half of the project,if i got the java code for image parts replacing,i completed my project...plzzz plzzz help me

Unknown said...

Hello
your post is really helpful. i tried both the splitting and merging. it has a problem of rounding. for example i split my image 574 * 574 in to 4 * 4 chunks which results in 143 * 143 sized 16 chunks and when i merge all the chunks the resultant size will be the 572 * 572 , because it does not take care of rounding mistake happens with division operation. if we make more chunks say 200 then the rounding loss 100 pixels and so on.

Unknown said...

thank u very much.........

Prateek Shrivastava said...

I am getting a black image after concating the images. Any idea?

Unknown said...

Works like a charm.

Unknown said...

sir,
Could you please tell me if we can import this into an android project ?
And if Yes How should we go about it.

Unknown said...

gud afternoon madam .madam i excute that code not run in netbeens .

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

view plainprint?

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

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

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

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

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

Unknown said...

above code is not excute please slove that code

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

Hi Kalani,
I am Sunil From Mumbai. I want take multiple images from DB and make one image and fetch that one image from server side to client and again extract that one image get multiple, so can we get this. Can you help me. my email id is sunilkale24@gmail.com

Unknown said...

This is very helpful for the works. Thank u as a srilankan

IlayaDrafts said...

Good morning mam.do you hav the code to crop a img

IlayaDrafts said...

This code shows the error
Cant find symbol ImageIO.read();
and ImageIO.write();

Unknown said...

i have to merge images of 30 MP resulting image will be 2*2 i.e 120 MP so i am getting out of memory error
what can i do can anyone help me

Shashank(admin) said...

Hi Kalyani
What If I have a fifth image which is png and want to overlay above this collage. So that transparent area remains transparent in png image. Please help

Unknown said...

A new tool constructed for merging PDF documents doesn’t lag behind. You may combine pdfs online without extra efforts. In the best traditions of our platform, the procedure is self-explanatory and easy in usage. Our user-friendly interface attracts your attention to main moments and step-by-step leads you to the successful result.merge, altomerge, merging PDF documents, combine pdfs online

If you need any information just click here pdf merge

Unknown said...

Best selenium online training institute `

vijay said...

I like your post very much. It is very much useful for my research. I hope you to share more info about this. Keep posting!!
aws Training in Bangalore
python Training in Bangalore
hadoop Training in Bangalore
angular js Training in Bangalore
bigdata analytics Training in Bangalore
python Training in Bangalore
aws Training in Bangalore

Durai Moorthy said...

I am really happy with your blog because your article is very unique and powerful for new reader.
aws Training in Bangalore
python Training in Bangalore
hadoop Training in Bangalore
angular js Training in Bangalore
bigdata analytics Training in Bangalore
python Training in Bangalore
aws Training in Bangalore

Rajesh Anbu said...

Thank you for sharing information. Wonderful blog & good post.
aws Training in Bangalore
python Training in Bangalore
hadoop Training in Bangalore
angular js Training in Bangalore
bigdata analytics Training in Bangalore
python Training in Bangalore
aws Training in Bangalore

Gerard Parsons said...

Quality of an image in a document printed out should always be higher than the quality of one being viewed on the internet as when a image is printed out it needs higher quality than an image that you view on your computer. onlineconvertfree.com

Anonymous said...

Asking questions are really pleasant thing if you are not understanding anything entirely, but this article offers nice understanding yet.
Mac Crack Software

Persephone Summers said...

buy juicy fruit online
buy gelato strain online
Buy dark star strain online
buy hawaiian skunk strain online
buy bc big bud strain leafly
buy auto flowering seeds online
buy brass knuckles vape recall 2018
buy alaskan thunder fuck online
buy cannabis seeds bank online

Vicky said...


Thanks for updating us with useful information
Techviky.com

Vicky said...


Thanks for updating us with useful information
Techviky.com

Vicky said...

Thanks for updating us with useful information

420marijuanamemes said...

best weed market
buy medical weed online
buy granddaddy purple weed online
buy white widows strain online
buy gelato strain exotic online
buy og kush strain online
moon rocks for sale online
buy silver haze strain online

420marijuanamemes said...

amf og
atomik moon rocks
ambrosia strain
blue dream vs og kush
citrix leafly
citrix strain
eleven roses strain
gorilla gas strain
pootie tang strain
pootie tang strain
laughing gym look alikes

NJC said...

https://www.facebook.com/Jack-russell-puppies-looking-for-a-lovely-home-103472108733880/

tommy said...
This comment has been removed by the author.
rj zz said...

OriginMushrooms.org is an online Magic Mushrooms Dispensary in USA. Shop the largest selection of dried mushrooms, Psilocybin edibles and Microdose capsule pills

buy ragdollcatkitten online said...

buy ragdollcatkitten online

https://ntoto77.com/ said...

※토토사이트※메이저사이트※사설토토※
오랫동안 많은 업체들과 함께 데이터 베이스를
구축하였으며 유져님들께서 안전한 놀이터
및 메이저 사이트에서 부담없이
최적의 스포츠게임을 즐기실수 있게 최고의
토토사이트를 제공해드립니다
※토토사이트 검증※토토사이트
추천받으실수 있습니다.

Bills said...

Nice Article Thanks for this info.

VISIT US said...

Proceeded with instructive choices will efficiently, such as white stable light co. Great on sign in should get into the worker entrance will give of installments. Multi month following the left portion of the key phrase. As soon as you can permit you need to share your company related to love during the accreditation. Entryway establishment direct you will need to land their standing chances to your

야한동영상
오피헌터
타이마사지
안마
바카라사이트

roulettesitetop said...

I was surfing the Internet for information and came across your blog. I am impressed by the information you have on this blog. It shows how well you understand this subject. 룰렛사이트탑

sheaul said...

have a peek at this website dolabuy gucci view it now buy replica bags online her comment is here replica designer bags wholesale

phane said...

find out here https://www.dolabuy.co Your Domain Name Dolabuy Loewe read what he said view website

thasot said...

top article replica dolabuy go to website 7a replica bags wholesale you could try this out buy replica bags

This is gorgeous, Rins. I wish I could do freehand designs. I can't believe how wonderful they are, and so neat. I imagine if I tried they'd be all over the nails except where I wanted them. Thanks fo said...

I appreciate several from the Information which has been composed, and especially the remarks posted I will visit once more.

https://filmeshot.com/videography/wedding/best-wedding-videographer-in-rajasthan/(opens in a new tab)

celebcarcollectionandbiography said...

https://howtofixgadgets.com/how-to-fix-redmi-y3-fingerprint-sensor-not-working-problem/

celebcarcollectionandbiography said...

https://howtofixgadgets.com/boat-airdopes-441-left-earbud-not-working-problem-fix-it/

celebcarcollectionandbiography said...

https://howtofixgadgets.com/poco-f1-proximity-sensor-not-working-problem-solution/

celebcarcollectionandbiography said...

https://howtofixgadgets.com/poco-x3-dead-poco-x3-black-screen-of-death-problem-solution/

celebcarcollectionandbiography said...

https://howtofixgadgets.com/horizontal-lines-on-laptop-screen-fix-solve-it-within-few-minutes/

celebcarcollectionandbiography said...

https://howtofixgadgets.com/how-to-fix-mouse-scroll-wheel-problem/

celebcarcollectionandbiography said...

https://howtofixgadgets.com/iphone-charging-port-not-working-fix-charging-port-iphone/

celebcarcollectionandbiography said...

https://okadtech.com/my-dell-inspiron-laptop-wont-turn-on/

Aperture2 said...

Excellent article! Thank you!  Digital marketing courses in Albania 

celebcarcollectionandbiography said...

https://okadtech.com/1990-to-2000-telugu-hit-songs-free-download/

priyankarajput said...

Thank you for sharing! I always appreciate engaging with such high-quality content that offers valuable insights. The presented ideas are not only excellent but also remarkably innovative, adding a cool and enjoyable touch to the post. Keep up the fantastic work.
visit: Financial Data Analytics: Risk Management and Investment Strategies

iteducationcentre said...

Thanks for sharing such an useful and informative blog with us.
Java classes in Pune

Related Posts with Thumbnails