RenderScript删除位图上带有alpha的像素

问题描述 投票:0回答:1

[我有一个位图,我需要删除所有具有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;
}

并且它工作正常,但缓慢地,一个位图的处理大约需要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;
}

和我的.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;
}
}

所以我在多个位图上使用此方法-最初,位图可以正常工作,但会收到损坏的图像。顺便说一下,当我在第一个位图上再次应用此方法时,它也会损坏它。似乎没有封闭的内存分配或共享资源idk。

有什么想法吗?也许有一个更简单的解决方案?提前谢谢大家!

android image-processing bitmap renderscript
1个回答
0
投票

实际上,您可以使用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;
}
© www.soinside.com 2019 - 2024. All rights reserved.