Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Bitmap: Convert transparent pixels to a color

Tags:

I have an Android app that loads an image as a bitmap and displays it in an ImageView. The problem is that the image appears to have a transparent background; this causes some of the black text on the image to disappear against the black background.

If I set the ImageView background to white, that sort of works, but I get ugly big borders on the image where it is stretched to fit the parent (the actual image is scaled in the middle).

So - I want to convert the transparent pixels in the Bitmap to a solid colour - but I cannot figure out how to do it!

Any help would be appreciate!

Thanks Chris

like image 349
ccbunney Avatar asked Jan 25 '13 23:01

ccbunney


2 Answers

If you are including the image as a resource, it is easiest to just edit the image yourself in a program like gimp. You can add your background there, and be sure of what it is going to look like and don't have use to processing power modifying the image each time it is loaded.

If you do not have control over the image yourself, you can modify it by doing something like, assuming your Bitmap is called image.

Bitmap imageWithBG = Bitmap.createBitmap(image.getWidth(), image.getHeight(),image.getConfig());  // Create another image the same size
imageWithBG.eraseColor(Color.WHITE);  // set its background to white, or whatever color you want
Canvas canvas = new Canvas(imageWithBG);  // create a canvas to draw on the new image
canvas.drawBitmap(image, 0f, 0f, null); // draw old image on the background
image.recycle();  // clear out old image 
like image 157
iagreen Avatar answered Sep 23 '22 13:09

iagreen


You can loop through each pixel and check if it is transparent.

Something like this. (Untested)

        Bitmap b = ...;
        for(int x = 0; x<b.getWidth(); x++){
            for(int y = 0; y<b.getHeight(); y++){
                if(b.getPixel(x, y) == Color.TRANSPARENT){
                    b.setPixel(x, y, Color.WHITE);
                }
            }
        }
like image 31
MrZander Avatar answered Sep 24 '22 13:09

MrZander