Wednesday 22 August 2012

Image (Split and merge)

This blog is useful to split and merge image in android.
This application will for merging number of smaller chunks to make the origina.So for that we need.some smaller image chunks. here  programmatically first split an image to get the smaller image chunks
and then merge them to get the original one.
         
    If you want you can also get some smaller chunks and directly merge them.    
        The below 4 lines of code does the splitting operation.   
        
        ImageView image = new ImageView(getApplicationContext());
        image.setImageResource(R.drawable.star);
        int chunkNumbers = 25;
        smallImages = splitImage(image, chunkNumbers);


Here as given below code you can split image .
in spliteImage() method pass ImageView object and chunkNumber.
chunkNumber = chunkNumbers is to tell how many chunks the image should split.
This method return ArrayList<Bitmap> of bitmap which set into grid view.

private void splitImage(ImageView image, int chunkNumbers) {
//For the number of rows and columns of the grid to be displayed
int rows,cols;
//For height and width of the small image chunks
int chunkHeight,chunkWidth;
//To store all the small image chunks in bitmap format in this list
ArrayList<Bitmap> chunkedImages = new ArrayList<Bitmap>(chunkNumbers);
//Getting the scaled bitmap of the source image
BitmapDrawable drawable = (BitmapDrawable) image.getDrawable();
Bitmap bitmap = drawable.getBitmap();
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth(), bitmap.getHeight(), true);
rows = cols = (int) Math.sqrt(chunkNumbers);
chunkHeight = bitmap.getHeight()/rows;
chunkWidth = bitmap.getWidth()/cols;
//xCoord and yCoord are the pixel positions of the image chunks
int yCoord = 0;
for(int x=0; x<rows; x++){
int xCoord = 0;
for(int y=0; y<cols; y++){
chunkedImages.add(Bitmap.createBitmap(scaledBitmap, xCoord, yCoord, chunkWidth, chunkHeight));
xCoord += chunkWidth;
}
yCoord += chunkHeight;
}
}

      Result is shown below. 


Alos we can merge image by using this method

Bitmap bitmap = Bitmap.createBitmap(chunkWidth * 5, chunkHeight * 5, Bitmap.Config.ARGB_4444);
//create a canvas for drawing all those small images
Canvas canvas = new Canvas(bitmap);
int count = 0;
for(int rows = 0; rows < 5; rows++){
for(int cols = 0; cols < 5; cols++){
canvas.drawBitmap(smallImages.get(count), chunkWidth * cols, chunkHeight * rows, null);
count++;
}
}

here, bitmap which set into imageview as shown below.
ImageView image = (ImageView) findViewById(R.id.source_image);
image.setImageBitmap(bitmap);
          Result is shown below.


1 comment:

Copy and share your useful data from Google chrome browser to your application in android.

Here In this blog I explain that how to copy and share your useful data from chrome browser in android. 1) How to show your applic...