我有我在我的应用程序中显示的图像.它们是从网上下载的.这些图像是几乎白色背景上的对象的图片.我希望这个背景是白色的(#FFFFFF).我想,如果我看一下像素0,0(应该总是灰白色),我可以得到颜色值并用白色替换图像中的每个像素.
之前已经问过这个问题,答案似乎是这样的:
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);
Run Code Online (Sandbox Code Playgroud)
但是,这不起作用.
运行此代码后,整个图像似乎是我想要删除的颜色.如同,现在整个图像是1纯色.
我也希望不必遍历整个图像中的每个像素.
有任何想法吗?
Ray*_*kud 15
这是我为您创建的方法,可以替换您想要的颜色.请注意,所有像素都将在位图上扫描,只有相同的像素才会替换为您想要的像素.
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;
}
Run Code Online (Sandbox Code Playgroud)
我希望有帮助:)