Color swap in bitmap

I have images that I display in my application. They are downloaded from the Internet. These images are images of objects on an almost white background. I want this background to be white (#FFFFFF). I believe that if I look at the pixel 0,0 (which should always be off-white), I can get the color value and replace each pixel in the image with this value with white.

This question has been asked before, and the answer seems to be as follows:

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); 

However, this does not work.

After running this code, the whole image seems to be the color that I wanted to delete. As now, the entire image is now solid.

I also hoped that you would not have to iterate over every pixel in the whole image.

Any ideas?

+7
android bitmap
source share
1 answer

Here is the method I created for you to replace a specific color for the one you want. Please note that all pixels will be scanned in a bitmap, and only those that are equal will be replaced with the one you want.

  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(pixel); R = Color.red(pixel); G = Color.green(pixel); B = Color.blue(pixel); 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 this helps :)

+13
source share

All Articles