【问题标题】:Convert white color to transparent on bitmap in android在android的位图上将白色转换为透明
【发布时间】:2015-03-17 03:36:22
【问题描述】:

我想在 android 位图中将白色背景转换为透明背景。

我的情况:

原始图片:我无法发布图片

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 bitmap mask color, remove color

【问题讨论】:

  • 这是因为 Color.white 是 FFFFFFFF。然而 FFFFFFFE 仍然是白的,但不会被这个算法捕捉到。该算法仅适用于精心制作的图像。
  • 感谢您的评论。我不明白你的意思..?那么,我不能解决这个问题吗?
  • VVB ,您的解决方案不要使用我的情况,因为我不使用 R.imagefile 的 XML。因此,如果您知道其他解决方案,请写信至此处。

标签: android colors bitmap background transparent


【解决方案1】:
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);
}

只需像上面的代码那样替换一行,它就会做你想做的事 - 用透明替换白色

在小米 Note 7 上工作 - 奥利奥

【讨论】:

    猜你喜欢
    • 2012-08-07
    • 1970-01-01
    • 2013-01-09
    • 2020-11-29
    • 2012-11-05
    • 1970-01-01
    • 1970-01-01
    • 2020-12-30
    • 2016-06-22
    相关资源
    最近更新 更多