Replacing a color in a Bitmap

后端 未结 1 836
我在风中等你
我在风中等你 2021-02-06 04:45

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 wh

相关标签:
1条回答
  • 2021-02-06 05:19

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

    0 讨论(0)
提交回复
热议问题