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:

  1. This was very helpful. Thank you!

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

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

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

    Anyway thanks a lot!

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

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

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

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

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

    ReplyDelete
  10. thank u very much.........

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

    ReplyDelete
  12. Works like a charm.

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

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

    ReplyDelete
  15. This comment has been removed by the author.

    ReplyDelete
  16. 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"));

    ReplyDelete
  17. above code is not excute please slove that code

    ReplyDelete
  18. This comment has been removed by the author.

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

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

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

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

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

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

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

    ReplyDelete
  26. Best selenium online training institute `

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

    ReplyDelete
  28. Anonymous10:19 PM

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

    ReplyDelete

  29. Thanks for updating us with useful information
    Techviky.com

    ReplyDelete

  30. Thanks for updating us with useful information
    Techviky.com

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

    ReplyDelete
  32. This comment has been removed by the author.

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

    ReplyDelete
  34. Nice Article Thanks for this info.

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

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

    ReplyDelete
  36. 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. 룰렛사이트탑

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

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

    ReplyDelete
  39. 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)

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

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

    ReplyDelete
  42. Anonymous11:11 AM

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

    ReplyDelete