簡體   English   中英

RenderScript 刪除 bitmap 處帶有 alpha 的像素

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM