3
votes

I want to convert white background to transparent background in android bitmap.

My situation:

Original Image : I cannot post a image

public Bitmap replaceColor(Bitmap src){
    if(src == null)
        return null;
    int width = src.getWidth();
    int height = src.getHeight();
    int[] pixels = new int[width * height];
    src.getPixels(pixels, 0, width, 0, 0, width, height);
    for(int x = 0;x < pixels.length;++x){
        pixels[x] = ~(pixels[x] << 8 & 0xFF000000) & Color.BLACK;
    }
    Bitmap result = Bitmap.createBitmap(pixels, width, height, Bitmap.Config.ARGB_8888);
    return result;
    }

Processing After It was detect pixel to pixel, one by one. It's good but this bitmap image doesn't remain original color.

So, I append code to filter.

if (pixels[x] == Color.white)

    public Bitmap replaceColor(Bitmap src){
    if(src == null)
        return null;
    int width = src.getWidth();
    int height = src.getHeight();
    int[] pixels = new int[width * height];
    src.getPixels(pixels, 0, width, 0, 0, width, height);
    for(int x = 0;x < pixels.length;++x){
        if(pixels[x] == Color.WHITE){
          pixels[x] = ~(pixels[x] << 8 & 0xFF000000) & Color.BLACK;
        }   
    }
    Bitmap result = Bitmap.createBitmap(pixels, width, height, Bitmap.Config.ARGB_8888);
    return result;
    }

Processing After,

But, this picture can not remove completely color white. So, It is not pretty.

I really want remove white background in android bitmap

My code is following in under stackoverflow article.

Android bitmap mask color, remove color

1
This is because Color.white is FFFFFFFF. However FFFFFFFE is still white to the eye, but won't be caught by this algorithm. That algorithm will only work for very carefully crafted images.Gabe Sechan
Thank you your comment. I don't understand what do you mean .. ? So, I can not solve this problem?임지욱
VVB , your solution don't use my case, because I don't use XML of R.imagefile. So if you know other solution, please write to here.임지욱

1 Answers

1
votes
public Bitmap replaceColor(Bitmap src) {
    if (src == null)
        return null;
    int width = src.getWidth();
    int height = src.getHeight();
    int[] pixels = new int[width * height];
    src.getPixels(pixels, 0, 1 * width, 0, 0, width, height);
    for (int x = 0; x < pixels.length; ++x) {
    //    pixels[x] = ~(pixels[x] << 8 & 0xFF000000) & Color.BLACK;
        if(pixels[x] == Color.WHITE) pixels[x] = 0;
    }
    return Bitmap.createBitmap(pixels, width, height, Bitmap.Config.ARGB_8888);
}

Just replace one line as in code above and it should do what you want it to - replace white color with transperent

Working on Mi Note 7 - Oreo