Android 替换位图中的颜色
我在我的应用程序中显示图像。它们是从网上下载的。这些图像是几乎白色背景上的物体图片。我希望这个背景是白色的。我想,如果我看像素0,0(应该一直是白色),我可以得到颜色值,并用白色替换图像中具有该值的每个像素 以前有人问过这个问题,答案似乎是:Android 替换位图中的颜色,android,bitmap,Android,Bitmap,我在我的应用程序中显示图像。它们是从网上下载的。这些图像是几乎白色背景上的物体图片。我希望这个背景是白色的。我想,如果我看像素0,0(应该一直是白色),我可以得到颜色值,并用白色替换图像中具有该值的每个像素 以前有人问过这个问题,答案似乎是: int intOldColor = bmpOldBitmap.getPixel(0,0); Bitmap bmpNewBitmap = Bitmap.createBitmap(bmpOldBitmap.getWidth(), bmpOldBitmap.g
int intOldColor = bmpOldBitmap.getPixel(0,0);
Bitmap bmpNewBitmap = Bitmap.createBitmap(bmpOldBitmap.getWidth(), bmpOldBitmap.getHeight(), Bitmap.Config.RGB_565);
Canvas c = new Canvas(bmpNewBitmap);
Paint paint = new Paint();
ColorFilter filter = new LightingColorFilter(intOldColor, Color.WHITE);
paint.setColorFilter(filter);
c.drawBitmap(bmpOriginal, 0, 0, paint);
然而,这是行不通的
运行此代码后,整个图像似乎就是我想要删除的颜色。如中所示,整个图像现在为1纯色
我还希望不必在整个图像中循环每个像素
有什么想法吗?这是我为您创建的一种方法,可以将特定颜色替换为您想要的颜色。请注意,位图上的所有像素都将被扫描,只有相等的像素将被替换为所需的像素
private Bitmap changeColor(Bitmap src, int colorToReplace, int colorThatWillReplace) {
int width = src.getWidth();
int height = src.getHeight();
int[] pixels = new int[width * height];
// get pixel array from source
src.getPixels(pixels, 0, width, 0, 0, width, height);
Bitmap bmOut = Bitmap.createBitmap(width, height, src.getConfig());
int A, R, G, B;
int pixel;
// iteration through pixels
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) {
// get current index in 2D-matrix
int index = y * width + x;
pixel = pixels[index];
if(pixel == colorToReplace){
//change A-RGB individually
A = Color.alpha(colorThatWillReplace);
R = Color.red(colorThatWillReplace);
G = Color.green(colorThatWillReplace);
B = Color.blue(colorThatWillReplace);
pixels[index] = Color.argb(A,R,G,B);
/*or change the whole color
pixels[index] = colorThatWillReplace;*/
}
}
}
bmOut.setPixels(pixels, 0, width, 0, 0, width, height);
return bmOut;
}
私有位图更改颜色(位图src、int color替换、int color替换){
int width=src.getWidth();
int height=src.getHeight();
int[]像素=新int[宽度*高度];
//从源获取像素阵列
getPixels(像素,0,宽度,0,0,宽度,高度);
Bitmap bmOut=Bitmap.createBitmap(宽度、高度,src.getConfig());
int A,R,G,B;
整数像素;
//像素迭代
对于(int y=0;y
我希望这有帮助:)这里的LightingColorFilter使用肯定不会像您预期的那样工作,因为没有任何说明“仅将此操作应用于此颜色”。第一个参数颜色是应用于图像中每个像素的乘法因子。第二个参数,白色(0xFFFFFF)被添加到每个像素,使整个东西变白。我明白了。那么我该如何替换特定的颜色呢?@MustanserIqbal您的位图是可变的吗?是的,它是可变的。。我对此不太了解,但当我从图库加载图像时,它需要可变。。如果是,则我的图像是可变的。新颜色的装配应在循环外完成,以减少完成此方法的总时间。