用红色替换位图中的黑色

22

在Android中,我如何通过编程将位图中的黑色(或任何其他颜色)替换为红色?(忽略透明度)尽管我已经可以用一种颜色替换位图中的白色,但是使用相同方法似乎无法替换黑色。

谢谢帮助。

3个回答

40

使用以下方法获取位图中的所有像素:

int [] allpixels = new int [myBitmap.getHeight() * myBitmap.getWidth()];

myBitmap.getPixels(allpixels, 0, myBitmap.getWidth(), 0, 0, myBitmap.getWidth(), myBitmap.getHeight());

for(int i = 0; i < allpixels.length; i++)
{
    if(allpixels[i] == Color.BLACK)
    {
        allpixels[i] = Color.RED;
    }
}

myBitmap.setPixels(allpixels,0,myBitmap.getWidth(),0, 0, myBitmap.getWidth(),myBitmap.getHeight());

1
感谢您提供的解决方案。它非常有效 - 只是我的PNG似乎有一些透明度的阴影,使用这种方法后,图形仍然会出现黑色(或灰色)边框,应该用适当的红色替换。 - Dominik
你如何初始化pixels[]? - TharakaNirmana
嘿 @孔子,我已经尝试了这里的解决方案。但是我想用透明背景替换白色。这里的解决方案可以更改颜色,但我能否将任何颜色更改为透明背景呢?你有什么线索吗? - Dory
我该如何使用十六进制字符串 #FFFFFF 替换为 #000000? - Ashish Sahu
请记住,您的 Bitmap 需要是 mutable,这样才不会抛出 IllegalStateException 异常。 - Bartek Lipinski
在PNG图像中填充整个空间时,颜色填充并不完美。 - JosephM

5

这对我有效

    public Bitmap replaceColor(Bitmap src,int fromColor, int targetColor) {
    if(src == null) {
        return null;
    }
    // Source image size
    int width = src.getWidth();
    int height = src.getHeight();
    int[] pixels = new int[width * height];
    //get pixels
    src.getPixels(pixels, 0, width, 0, 0, width, height);

    for(int x = 0; x < pixels.length; ++x) {
        pixels[x] = (pixels[x] == fromColor) ? targetColor : pixels[x];
    }
    // create result bitmap output
    Bitmap result = Bitmap.createBitmap(width, height, src.getConfig());
    //set pixels
    result.setPixels(pixels, 0, width, 0, 0, width, height);

    return result;
}

现在设置您的位图。
replaceColor(bitmapImg,Color.BLACK,Color.GRAY  )

For better view please check this Link


0

@nids:你尝试过将你的Color替换为Color.TRANSPARENT吗?那应该可以解决问题...


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