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

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.


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);

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

Tags:

Android