Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 854
임지욱 Avatar asked Sep 18 '25 12:09

임지욱


1 Answers

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

like image 192
mayank1513 Avatar answered Sep 20 '25 05:09

mayank1513