在安卓系统中将位图的白色转换为透明色

4
我希望将安卓位图的白色背景转换为透明背景。我的情况是:原始图片——我无法发布图片。
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;
    }

在像素点一一检测后,需要进行处理。这样做很好,但是位图图像的原始颜色并没有保留。

因此,我添加了过滤器代码。

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;
    }

处理之后,

但是,这张图片无法完全去掉白色。因此,它不太好看。

我真的想在Android位图中去除白色背景。

我的代码如下所示,在stackoverflow文章中:

Android位图掩码颜色,去除颜色


这是因为Color.white是FFFFFFF。然而,对于肉眼来说,FFFFFFFE仍然是白色的,但不会被此算法捕捉到。该算法只适用于非常精心制作的图像。 - Gabe Sechan
谢谢您的评论。我不明白您的意思...?那么,我无法解决这个问题吗? - 임지욱
https://dev59.com/wXI_5IYBdhLWcg3wK_3E - VVB
VVB,你的解决方案不适用于我的情况,因为我没有使用R.imagefile的XML。所以如果你知道其他的解决方案,请在这里写下来。 - 임지욱
1个回答

3
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);
}

只需像上面代码中的一行那样替换,它就可以实现您想要的效果 - 将白色替换为透明色

在Mi Note 7上工作 - Oreo系统


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接