Need help?

I'm available for remote short term contracting or consultancy work. Please check out my LinkedIn profile for more details on my experience.

Please feel free to use the form below to contact me.




Combining 2 Images in Android using Canvas

This article goes through the process of combining 2 images (only works with PNG or JPG ). It will involve passing 2 Bitmaps, which will then get combined using the Canvas class - sounds simple huh?

Well, it is pretty simple - here is the whole function below:


  public Bitmap combineImages(Bitmap c, Bitmap s) { // can add a 3rd parameter 'String loc' if you want to save the new image - left some code to do that at the bottom
    Bitmap cs = null;

    int width, height = 0;
    
    if(c.getWidth() > s.getWidth()) {
      width = c.getWidth();
      height = c.getHeight() + s.getHeight();
    } else {
      width = s.getWidth();
      height = c.getHeight() + s.getHeight();
    }

    cs = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

    Canvas comboImage = new Canvas(cs);

    comboImage.drawBitmap(c, 0f, 0f, null);
    comboImage.drawBitmap(s, 0f, c.getHeight(), null);

    // this is an extra bit I added, just incase you want to save the new image somewhere and then return the location
    /*String tmpImg = String.valueOf(System.currentTimeMillis()) + ".png";

    OutputStream os = null;
    try {
      os = new FileOutputStream(loc + tmpImg);
      cs.compress(CompressFormat.PNG, 100, os);
    } catch(IOException e) {
      Log.e("combineImages", "problem combining images", e);
    }*/

    return cs;
  }

In the function we create a temporary Bitmap, which will be the new container for both the images you wish to merge. Once we have our new Bitmap created, we use that to build the new Canvas - this is what we use for drawing the other 2 images on.

This example stacks the images - 'c' being on the top and 's' being at the bottom, but you can modify this to lay them out any way you like.

You can also save the newly created image if you want - I commented that part out, but you can uncomment that and just return a String to the saved location. Currently it's just returning the new Bitmap that was just created with the combined images.

Hope this article was helpful, and feel free to ask any questions.


jon | September 10, 2010 | Comments (4)

Comments

Yeah its great.. thank you... but i have nine images to join . will you please help me .
Thank You
Comment by Avinash - April 22, 2015 @ 2:39 am
Tyring
Comment by saraswathi - June 14, 2014 @ 11:08 am
Wow, This is really going to help me out. Thanks for sharing the info.
Comment by Jordan - February 14, 2014 @ 9:47 am
Wow, This is really going to help me out. Thanks for sharing the info.
Comment by Jordan - June 29, 2012 @ 9:52 am

Name (required)
Email (will not be published) (required)
Website

captcha