简体   繁体   中英

Android Bitmap: Convert transparent pixels to a color

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

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 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM