我想在 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
最佳答案
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 - 奥利奥
关于android - 在android的位图上将白色转换为透明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29090880/