Replacing A Color In A Bitmap
I have images which I display in my app. They are downloaded from the web. These images are pictures of objects on an almost-white background. I want this background to be white
Solution 1:
Here is a method I created for you to replace a specific color for the one you want. Note that all the pixels will get scanned on the Bitmap and only the ones that are equal will be replaced for the one you want.
private Bitmap changeColor(Bitmap src, int colorToReplace, int colorThatWillReplace) {
intwidth= src.getWidth();
intheight= src.getHeight();
int[] pixels = newint[width * height];
// get pixel array from source
src.getPixels(pixels, 0, width, 0, 0, width, height);
BitmapbmOut= Bitmap.createBitmap(width, height, src.getConfig());
int A, R, G, B;
int pixel;
// iteration through pixelsfor (inty=0; y < height; ++y) {
for (intx=0; x < width; ++x) {
// get current index in 2D-matrixintindex= 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;
}
I hope that helped :)
Post a Comment for "Replacing A Color In A Bitmap"