[英]RenderScript remove pixels with alpha at bitmap
我有一个 bitmap,我需要删除所有具有 alpha 的像素。 听起来很容易,但我坚持下去。 我有这个 Java 代码:
public static Bitmap overdrawAlphaBits(Bitmap image, int color) {
Bitmap coloredBitmap = image.copy(Bitmap.Config.ARGB_8888, true);
for (int y = 0; y < coloredBitmap.getHeight(); y++) {
for (int x = 0; x < coloredBitmap.getWidth(); x++) {
int pixel = coloredBitmap.getPixel(x, y);
if (pixel != 0) {
coloredBitmap.setPixel(x, y, color);
}
}
}
return coloredBitmap;
}
它工作正常,但速度很慢,处理一个 bitmap 大约需要 2 秒。 我正在尝试使用 RenderScript。 它工作得很快,但不稳定。 这是我的代码:
public static Bitmap overdrawAlphaBits(Bitmap image, Context context) {
Bitmap blackbitmap = Bitmap.createBitmap(image.getWidth(), image.getHeight(), image.getConfig());
RenderScript mRS = RenderScript.create(context);
ScriptC_replace_with_main_green_color script = new ScriptC_replace_with_main_green_color(mRS);
Allocation allocationRaster0 = Allocation.createFromBitmap(mRS, image, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT);
Allocation allocationRaster1 = Allocation.createTyped(mRS, allocationRaster0.getType());
script.forEach_root(allocationRaster0, allocationRaster1);
allocationRaster1.copyTo(blackbitmap);
allocationRaster0.destroy();
allocationRaster1.destroy();
script.destroy();
mRS.destroy();
return blackbitmap;
}
和 my.rs 文件:
void root(const uchar4 *v_in, uchar4 *v_out) {
uint32_t rValue = v_in->r;
uint32_t gValue = v_in->g;
uint32_t bValue = v_in->b;
uint32_t aValue = v_in->a;
if(rValue!=0 || gValue!=0 || bValue!=0 || aValue!=0){
v_out->r = 0x55;
v_out->g = 0xED;
v_out->b = 0x69;
}
}
所以我在多个位图上使用这种方法 - 起初 bitmap 工作正常,但我收到损坏的图像。 顺便说一句,当我在第一个 bitmap 上再次应用此方法时,它也会损坏它。 貌似没有关闭 memory 分配或共享资源,idk。
请问有什么想法吗? 也许有更简单的解决方案? 提前谢谢大家!
实际上,您可以使用 getPixels 方法读取数组中的所有像素,然后对其进行操作。 它工作得足够快。 问题是 getPixel 工作缓慢。 所以这里是代码:
public static Bitmap overdrawAlphaBits(Bitmap image, int color) {
int[] pixels = new int[image.getHeight() * image.getWidth()];
image.getPixels(pixels, 0, image.getWidth(), 0, 0, image.getWidth(), image.getHeight());
for (int i = 0; i < image.getWidth() * image.getHeight(); i++) {
if (pixels[i] != 0) {
pixels[i] = color;
}
}
image.setPixels(pixels, 0, image.getWidth(), 0, 0, image.getWidth(), image.getHeight());
return image;
}
在 your.rs 文件中,我认为 rValue、gValue 等应该是 uchar 类型,而不是 uint32_t。 此外,if 语句缺少将 v_in 值复制到 v_out 的 else 子句,否则您将获得未定义的 output 值。 请注意,在您的 Java 代码中,output bitmap 被初始化为副本。 在 renderscript 代码中不是这种情况,您在其中创建与输入相同类型的 output 分配,但不会复制值。 因此,您需要复制 kernel 中的输入值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.