22

How can I replace the black color in a bitmap with red (or any other color) programmatically in Android (ignoring transparency)? I can replace the white color in the bitmap with a color already but it somehow does not work with black. Thanks for help.

Dominik
  • 1,703
  • 6
  • 26
  • 46

3 Answers3

39

Get all the pixels in the bitmap using this:

int [] allpixels = new int [myBitmap.getHeight() * myBitmap.getWidth()];

myBitmap.getPixels(allpixels, 0, myBitmap.getWidth(), 0, 0, myBitmap.getWidth(), myBitmap.getHeight());

for(int i = 0; i < allpixels.length; i++)
{
    if(allpixels[i] == Color.BLACK)
    {
        allpixels[i] = Color.RED;
    }
}

myBitmap.setPixels(allpixels,0,myBitmap.getWidth(),0, 0, myBitmap.getWidth(),myBitmap.getHeight());
Merthan Erdem
  • 5,598
  • 2
  • 22
  • 29
confucius
  • 13,127
  • 10
  • 47
  • 66
  • 1
    Thanks for the solution. Works great - only, my PNG seem to have some shades of transparency and with this method the graphic still gets a black (or gray) border which also should be replaced with the appropriate shade of red. – Dominik Aug 30 '11 at 03:23
  • How do you initialize the pixels[]? – TharakaNirmana Aug 11 '13 at 06:21
  • hey @confucius, i have tried solution here. But I want replace the white color with transparent background. solution here works for changing color can i change any color to transparent background. Do you have any clue of it. – Dory Aug 29 '13 at 06:46
  • how can i replace using hex string #FFFFFF to #000000 – Ashish Sahu May 24 '14 at 00:28
  • Remember that your `Bitmap` needs to be `mutable` for `setPixels(...)` not to throw an `IllegalStateException`. – Bartek Lipinski Apr 14 '15 at 14:47
  • filling color in whole space in case of png image,not worked perfectly. – JosephM Feb 19 '16 at 09:25
5

This works for me

    public Bitmap replaceColor(Bitmap src,int fromColor, int targetColor) {
    if(src == null) {
        return null;
    }
    // Source image size
    int width = src.getWidth();
    int height = src.getHeight();
    int[] pixels = new int[width * height];
    //get pixels
    src.getPixels(pixels, 0, width, 0, 0, width, height);

    for(int x = 0; x < pixels.length; ++x) {
        pixels[x] = (pixels[x] == fromColor) ? targetColor : pixels[x];
    }
    // create result bitmap output
    Bitmap result = Bitmap.createBitmap(width, height, src.getConfig());
    //set pixels
    result.setPixels(pixels, 0, width, 0, 0, width, height);

    return result;
}

Now set your bit map

replaceColor(bitmapImg,Color.BLACK,Color.GRAY  )

For better view please check this Link

DEVSHK
  • 833
  • 11
  • 10
0

@nids : Have you tried replacing your Color to Color.TRANSPARENT ? That should work...

rahil008
  • 173
  • 1
  • 7