Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the background color of a saved transparent bitmap

Tags:

I am opening a png image into a Bitmap, making some modifications to it and then saving it to disk as a jpg. In the case where the png has some transparent areas, they are saved as black. Is there a way to change this default behavior so the image is saved with a different color background such as white?

Thanks

like image 647
cottonBallPaws Avatar asked Dec 31 '10 22:12

cottonBallPaws


People also ask

Can a BMP file have a transparent background?

Yes, the bitmap format does support transparency.

How do I remove the white background from a bitmap image?

Go to Bitmaps > Bitmap Color Mask, confirm that Hide Colors is selected, and check the box for the first color selection slot. Select the eyedropper below the color selections and click the background color you want to remove. Click Apply when finished.


2 Answers

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

like image 125
Daren Robbins Avatar answered Oct 26 '22 09:10

Daren Robbins


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(); 
like image 30
Muhammed Refaat Avatar answered Oct 26 '22 08:10

Muhammed Refaat