Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace black color in bitmap with red

Tags:

android

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.

like image 559
Dominik Avatar asked Aug 30 '11 01:08

Dominik


2 Answers

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());
like image 84
confucius Avatar answered Dec 07 '22 15:12

confucius


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

like image 43
DEVSHK Avatar answered Dec 07 '22 16:12

DEVSHK