Android Bitmap: Convert transparent pixels to a color

前端 未结 2 1362
生来不讨喜
生来不讨喜 2021-01-01 16:35

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 so

相关标签:
2条回答
  • 2021-01-01 17:16

    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 
    
    0 讨论(0)
  • 2021-01-01 17:18

    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);
                    }
                }
            }
    
    0 讨论(0)
提交回复
热议问题