user65721
user65721

Reputation: 2923

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;
}

Upvotes: 1

Views: 711

Answers (1)

Stephen Hines
Stephen Hines

Reputation: 2622

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));
...

Upvotes: 2

Related Questions