Home » Android » android – Replacing a color in a Bitmap

android – Replacing a color in a Bitmap

Posted by: admin June 15, 2020 Leave a comment

Questions:

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 (#FFFFFF). I figure, if I look at pixel 0,0 (which should always be off-white), I can get the color value and replace every pixel in the image having that value with white.

This question has been asked before and the answer seems to be this:

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 isn’t working.

After running this code, the entire image seems to be the color I was wanting to remove. As in, the entire image is 1 solid color now.

I was also hoping to not have to loop through every pixel in the entire image.

Any ideas?

How to&Answers:

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

I hope that helped 🙂