简体   繁体   English

Android位图:将透明像素转换为颜色

[英]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. 我有一个Android应用程序,可以将图像作为位图加载并在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). 如果我将ImageView背景设置为白色,那种工作,但我在图像上得到了丑陋的大边框,它被拉伸以适合父级(实际图像在中间缩放)。

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 . 如果您将图像作为资源包含在内,最简单的方法就是在像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称为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);
                }
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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