How to combine two Bitmap in Android

This blog is about how to combine 2 images in Android programatically.

Note: -For this blog I am creating Bitmap instance from drawables. You can get from Camera/web APIs etc.

 1. Create 2 Bitmap instance from Drawable.
1
2
3
4
5
Bitmap image1 = BitmapFactory.decodeResource(getResources(),
                R.drawable.image_one);

        Bitmap image2 = BitmapFactory.decodeResource(getResources(),
                R.drawable.image_two);

2. Create methods combineBitmap with 2 arguments with type of Bitmap and return type is also Bitmap.
1
  public Bitmap combineImages(Bitmap bitmap1, Bitmap bitmap2){}

3. Create new instance of bitmap with bitmap2.
1
 Bitmap bit1 = Bitmap.createBitmap(bitmap2, 0, 0, bitmap2.getWidth(), bitmap2.getHeight(), null, true);

4. Create new Instance of Bitmap with bitmap1 which height is equals to height of bitmap1 and bitmap2.
1
        Bitmap cs = Bitmap.createBitmap(bitmap1.getWidth(), bitmap1.getHeight() +bitmap2.getHeight(), Bitmap.Config.ARGB_8888);

5. Create a canvas object.
1
 Canvas comboImage = new Canvas(cs);

6. Draw bitmap1 to canvas.
1
 comboImage.drawBitmap(bitmap1, 0.0f, 0.0f, null);

7. Draw second bitmap to canvas.which has margin to is height of bitmap1.
1
comboImage.drawBitmap(bit1, 0.0f, (float) bitmap1.getHeight(), null);

8. Return cs bitmap object.
1
return cs;

9. Full code of combineImage() is below.
1
2
3
4
5
6
7
8
9
 public Bitmap combineImages(Bitmap bitmap1, Bitmap bitmap2) {

      Bitmap bit1 = Bitmap.createBitmap(bitmap2, 0, 0, bitmap2.getWidth(), bitmap2.getHeight(), null, true);
        Bitmap cs = Bitmap.createBitmap(bitmap1.getWidth(), bitmap1.getHeight() +bitmap2.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas comboImage = new Canvas(cs);
        comboImage.drawBitmap(bitmap1, 0.0f, 0.0f, null);
        comboImage.drawBitmap(bit1, 0.0f, (float) bitmap1.getHeight(), null);
        return cs;
    }

This method return you combined bitmap object.

Happy Coding :D

Comments

Post a Comment

Popular posts from this blog

How to change the color of Hamburger icon in Toolbar Android

How to do Facebook Login with Custom Button Android