Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Canvas for merging two images in Android?

I want to create a combined image with two different images by overlapping.

For this My code is

  ImageView image = (ImageView) findViewById(R.id.imageView1);
  Drawable drawableFore = getResources().getDrawable(R.drawable.foreg);
  Drawable drawableBack = getResources().getDrawable(R.drawable.backg);

  Bitmap bitmapFore = ((BitmapDrawable) drawableFore).getBitmap();
  Bitmap bitmapBack = ((BitmapDrawable) drawableBack).getBitmap();

  Bitmap scaledBitmapFore = Bitmap.createScaledBitmap(bitmapFore, 35, 35, true);
  Bitmap scaledBitmapBack = Bitmap.createScaledBitmap(bitmapBack, 45, 45, true);

  Bitmap combineImages = overlay(scaledBitmapBack, scaledBitmapFore);

  image.setImageBitmap(combineImages);

overlay() method is

public static Bitmap overlay(Bitmap bmp1, Bitmap bmp2)
{
 try
 {
   Bitmap bmOverlay = Bitmap.createBitmap(bmp1.getWidth(), bmp1.getHeight(),  bmp1.getConfig());
   Canvas canvas = new Canvas(bmOverlay);
   canvas.drawBitmap(bmp1, new Matrix(), null);
   canvas.drawBitmap(bmp2, 0, 0, null);
   return bmOverlay;
 } catch (Exception e)
 {
    // TODO: handle exception
  e.printStackTrace();
  return null;
 }
}

case 1 :overlay method returns null in this case.

case 2: But when I switch images like I use background image for setting in foreground and foreground image for setting in background then code works fine.

but I want the first case should work properly but it is not. I am not getting why this is happening.

Please Help

like image 577
Arun Badole Avatar asked Dec 07 '11 13:12

Arun Badole


People also ask

How do I put two pictures together to make one Android?

In the file manager screen, tap the hamburger icon in the top-left and select Gallery. This will let you pick a photo from your Gallery app. Select the photos you want to combine into one and tap the checkmark in the top-right. Once your photos are in the app, tap Combine Images at the bottom.


1 Answers

I think it happens, because the 2nd bitmap is bigger in size. So try this:

public static Bitmap overlay(Bitmap bmp1, Bitmap bmp2)
{
 try
 {
   int maxWidth = (bmp1.getWidth() > bmp2.getWidth() ? bmp1.getWidth() : bmp2.getWidth());
   int maxHeight = (bmp1.getHeight() > bmp2.getHeight() ? bmp1.getHeight() : bmp2.getHeight());
   Bitmap bmOverlay = Bitmap.createBitmap(maxWidth, maxHeight,  bmp1.getConfig());
   Canvas canvas = new Canvas(bmOverlay);
   canvas.drawBitmap(bmp1, 0, 0, null);
   canvas.drawBitmap(bmp2, 0, 0, null);
   return bmOverlay;

 } catch (Exception e)
 {
    // TODO: handle exception
  e.printStackTrace();
  return null;
 }
}
like image 64
Caner Avatar answered Oct 19 '22 21:10

Caner