Overlay two bitmaps in android

In last post I explained how to reduce the size of bitmap. In this post I will explain how we can overlay two bitmaps.

The use case of this program is to fix resolution of the bitmap without changing the aspect ratio.

public static Bitmap overlay(Bitmap bmp1, Bitmap bmp2) {
        Bitmap bmOverlay = Bitmap.createBitmap(bmp1.getWidth(), bmp1.getHeight(), bmp1.getConfig());
        Canvas canvas = new Canvas(bmOverlay);
        canvas.drawBitmap(bmp1, new Matrix(), null);
        canvas.drawBitmap(bmp2,  (bmp1.getWidth()  - bmp2.getWidth()) /2, (bmp1.getHeight()  - bmp2.getHeight()) /2, null);
        return bmOverlay;

The above function takes two bitmaps and returns a single bitmap. This is very useful when we want to add a background colour or image on an existing bitmap.

How to resize bitmap

In this section I will show how to resize bitmap keeping the aspect ratio intact. Without changing the aspect ration bitmap can be manipulated and resized to any desired resolution.

public static Bitmap resizeBitmap(int scaleSize, Bitmap bitmap) {
        Bitmap resizedBitmap = null;
        int originalWidth = bitmap.getWidth();
        int originalHeight = bitmap.getHeight();
        int newWidth;
        int newHeight;
        float multFactor;
        if(originalHeight > originalWidth) {
            newHeight = scaleSize ;
            multFactor = (float) originalWidth/(float) originalHeight;
            newWidth = (int) (newHeight*multFactor);
        } else if(originalWidth > originalHeight) {
            newWidth = scaleSize ;
            multFactor = (float) originalHeight/ (float)originalWidth;
            newHeight = (int) (newWidth*multFactor);
        } else {
            newHeight = scaleSize ;
            newWidth = scaleSize ;
        resizedBitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, false);
        return resizedBitmap;
Bitmap resizedBitmap = resizeBitmap (512, bmp1);


createScaledBitmap: Creates a new bitmap, scaled from an existing bitmap, when possible. If the specified width and height are the same as the current width and height of the source bitmap, the source bitmap is returned and no new bitmap is created.

One Response

  1. fw March 7, 2020

Leave a Reply