java Android 位图:将透明像素转换为颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14531674/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android Bitmap: Convert transparent pixels to a color
提问by ccbunney
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.
我有一个 Android 应用程序,它将图像加载为位图并将其显示在 ImageView 中。问题是图像看起来有透明背景;这会导致图像上的一些黑色文本在黑色背景下消失。
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
谢谢克里斯
回答by iagreen
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.
如果您将图像作为资源包含在内,最简单的方法是在gimp 之类的程序中自己编辑图像。你可以在那里添加你的背景,并确定它会是什么样子,并且不必在每次加载时修改图像的处理能力。
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
回答by MrZander
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);
}
}
}