How to change the background color of a saved transparent bitmap How to change the background color of a saved transparent bitmap android android

How to change the background color of a saved transparent bitmap


You could draw it to a new bitmap, e.g.

   Bitmap newBitmap = Bitmap.createBitmap(image.getWidth(),     image.getHeight(), image.getConfig());    Canvas canvas = new Canvas(newBitmap);    canvas.drawColor(Color.WHITE);    canvas.drawBitmap(image, 0F, 0F, null);

then save new bitmap instead


To save an image and retain its transparent areas you can't save it as JPG, you have to save it as PNG, and not only that, but setting the setting of setHasAlpha() to true BEFORE saving the image, so it would be like that:

before saving:

mBitmap.setHasAlpha(true);

And when saving, save the image as PNG using whatever the method you are using for saving, for example:

File file = new File(folderDir, name);try {    file.createNewFile();} catch (IOException e) {    e.printStackTrace();}FileOutputStream out = new FileOutputStream(file);mBitmap.setHasAlpha(true);mBitmap.compress(Bitmap.CompressFormat.PNG, 80, out);out.flush();out.close();


For Kotlin you can use this Extension function

/** * Returns a new Bitmap with provided background color and recycles the current one. */fun Bitmap.changeBackgroundColor(color: Int): Bitmap {    val newBitmap = Bitmap.createBitmap(width, height, config)    val canvas = Canvas(newBitmap)    canvas.drawColor(color)    canvas.drawBitmap(this, 0F, 0F, null)    recycle()    return newBitmap}