简体   繁体   中英

How to live blur bitmap with renderscript?

I need to blur image with a SeekBar that lets user to control radius of the blur. I use this method below, however it seems wasting memory and time because of creating new bitmaps every function call when SeekBar value changed. What is the best approach for live blur implementation with RenderScript ?

 public static Bitmap blur(Context ctx, Bitmap image, float blurRadius) {
    int width = Math.round(image.getWidth() * BITMAP_SCALE);
    int height = Math.round(image.getHeight() * BITMAP_SCALE);        
    Bitmap inputBitmap = Bitmap.createScaledBitmap(image, width, height, false);          
    Bitmap outputBitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
    RenderScript rs = RenderScript.create(ctx);
    ScriptIntrinsicBlur theIntrinsic = ScriptIntrinsicBlur.create(rs,  Element.U8_4(rs));
    Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap);
    Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap);
    theIntrinsic.setRadius(blurRadius);
    theIntrinsic.setInput(tmpIn);
    theIntrinsic.forEach(tmpOut);
    tmpOut.copyTo(outputBitmap);
    rs.destroy();
    if(inputBitmap!=outputBitmap)
        inputBitmap.recycle();
    return outputBitmap;
}

These calls can be quite expensive and really should be done in an outer part of your application. You can then reuse the RenderScript context/object and ScriptIntrinsicBlur when you need them. You also should not destroy them when the function finishes (since you will be reusing them). For greater savings, you can pass the actual input/output bitmaps to your routine (or their Allocations) and keep those steady too. There really is a lot of dynamic creation/destruction in this snippet, and I can imagine that some of these things don't change frequently (and thus don't need to keep being recreated from scratch).

...
RenderScript rs = RenderScript.create(ctx);
ScriptIntrinsicBlur theIntrinsic = ScriptIntrinsicBlur.create(rs,  Element.U8_4(rs));
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM