임지욱
임지욱

Reputation: 43

Convert white color to transparent on bitmap in android

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

Upvotes: 4

Views: 3948

Answers (1)

Mayank Kumar Chaudhari
Mayank Kumar Chaudhari

Reputation: 18806

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

Upvotes: 3

Related Questions