Saturday, December 21, 2013

MERGE MULTIPLE IMAGES INTO ONE IMAGE IN ANDROID

Introduction: 


            This blog post is completely related to my previous post Splitting an image into smaller chunks. As far as the work is concerned both are responsible for completely opposite work. First one is responsible for splitting and this one is responsible for merging.

Where We Need This?


             As I said in my previous post this kind of splitting and merging concept is very much essential for sending and receiving larger image files across the web.
             My previous post will help you to send larger image files and this post will help you to merge the received image chunks to get the original one.

How To Achieve This?


We simply need to follow the following steps to achieve this.
  1. Get all the smaller image chunks.
  2. Find the width and height of those smaller images. (NOTE: all image chunks are of same size)
  3. Create a Bitmap with width = width_of_each_smaller_chunk * rows and                                                 height = height_of_each_smaller_chunk * columns.
  4. Create a Canvas encapsulating the Bitmap object in it.
  5. Now draw the smaller chunks on the Canvas object.

Source Code:


The below code snippet shows how to merge smaller image chunks into one.



Some Important points:


            Note that the actual code for merge operation is inside the onClick() method of the above code snippet. Below is the description about the variables of the onClick() method.
  1. chunkHeight & chunkWidth : Height and Width of smaller image chunks.
  2. smallImages : An ArrayList<Bitmap> object which stores all the smaller image chunks in their bitmap format.
  3. bitmap : The target bitmap which will represent the original image after merge.
  4. canvas : The canvas object encapsulating the target bitmap to draw the smaller image chunks.
You need to FOCUS more on the following line of code of onClick() method.



            The 3rd argument of the createBitmap() method is the configuration for the Bitmap. I used Bitmap.Config.ARGB_4444. Documentation recommends ARGB_8888 instead of ARGB_4444. As ARGB_8888 will give you more qualitative image, so there is every chance of getting BINDER TRANSACTION FAILED error if your device configuration is low. So I used ARGB_4444, if you are not getting any error with ARGB_8888, ten better go for that. For more information about these configuration see this.

Reference:


You can download the complete source code from My Google Drive Account.
If you want to achieve the same in Java using ImageIO, then you can see this.

Screen Shots:


Source Images
Source Images
Result Image
Result Image