Android: How to: create a new copy of an existing Bitmap?

Solution 1:

This answer helped me:

https://stackoverflow.com/a/17068594/1373248

The code is the following:

Bitmap bmp1 = BitmapFactory.decodeResource(cont.getResources(), R.drawable.image);
//then create a copy of bitmap bmp1 into bmp2
Bitmap bmp2 = bmp1.copy(bmp1.getConfig(), true);

Solution 2:

Depending on situation you can use:

Bitmap src = ...;
Bitmap dst = src.copy(src.getConfig(), src.isMutable);

The code below creates a copy. That means it copies the pixels from source bitmap and makes completely new Bitmap object. The reason why I am pointing it out because on internet you can find many examples where they use Bitmap.createBitmap() which does not guarantee if the new bitmap will be an object or a reference to older one. And depending on situation you can have problematic behaviour.

Solution 3:

Bitmap OLDBitmap = getBitmap();
Bitmap newBmp = Bitmap.createBitmap(OLDBitmap);

Solution 4:

public static Bitmap cloneBitmap(Bitmap bitmap) {
    return bitmap.copy(bitmap.getConfig(),bitmap.isMutable());
}