Android Renderscript: Gaussian Blur

Some of you might have stumbled upon problems with bluring in Android. Before Honeycomb (3.x) this was implemented "somewhat efficient by hardware" (quote from Android framework Engineer) and you could blur at least behind dialogs. Unfortunately you no longer have that option, gladly there is a solution (at least unless you want to blur dynamic content).

So here is a very basic and straight forward method to blur a Bitmap with API 17 and above (4.2.2+). Radius is a value between 0 and 25.

ATTENTION: It seems like there is a bug (currently Android 4.4.2) that forces apps to crash when using RenderScript on devices with a width of 2048 and bigger (like Nexus 10 ...). You can read more on that in the official Google Issue


private Bitmap  createBlurredImage (Bitmap originalBitmap, int radius)
 {
     // Create another bitmap that will hold the results of the filter.
     Bitmap blurredBitmap;
     blurredBitmap = Bitmap.createBitmap (originalBitmap);

     // Create the Renderscript instance that will do the work.
     RenderScript rs = RenderScript.create (this);

     // Allocate memory for Renderscript to work with
     Allocation input = Allocation.createFromBitmap (rs, originalBitmap, Allocation.MipmapControl.MIPMAP_FULL, Allocation.USAGE_SCRIPT);
     Allocation output = Allocation.createTyped (rs, input.getType());

     // Load up an instance of the specific script that we want to use.
     ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create (rs, Element.U8_4 (rs));
     script.setInput (input);

     // Set the blur radius
     script.setRadius (radius);

     // Start the ScriptIntrinisicBlur
     script.forEach (output);

     // Copy the output to the blurred bitmap
     output.copyTo (blurredBitmap);

     return blurredBitmap;
 }
Based on Xamarins tutorial.

Kommentare