Android ProTips: Blur Images Efficiently using Renderscript

Public on October 1, 2015
Blurring images is an effect a lot of developers need to achieve, and it may require some time and efforts to be implemented. Also, since a lot of image manipulation is required, if it's not appropriately coded it can be really a pain in terms of CPU and memory usage.

There's a quick and efficient solution to blur images, which is Renderscript.

Available since API 11 (Honeycomb), Renderscript allows to take advantage of the GPU acceleration and is targeted at high-performance 3D rendering and compute operations.
Renderscript is a really complex and articulated product, and allows deep configuration and coding using native C99 language, which allows portability, performance and usability.

However, since API 17 (4.2.2) Renderscript offer some built-in functions that perform well-defined operations, called Intrinsics.
Intrinsics are pre-written scripts that allow,  to perform operations like Blur, Blen, Matrix Convolution and more, without the need to write Renderscript code.

Here's a simple method I wrote to easily end efficiently apply a Blur filter to a Bitmap:

public Bitmap blurBitmap(Bitmap bitmap){

//Let's create an empty bitmap with the same size of the bitmap we want to blur
Bitmap outBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);

//Instantiate a new Renderscript
RenderScript rs = RenderScript.create(getApplicationContext());

//Create an Intrinsic Blur Script using the Renderscript
ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));

//Create the in/out Allocations with the Renderscript and the in/out bitmaps
Allocation allIn = Allocation.createFromBitmap(rs, bitmap);
Allocation allOut = Allocation.createFromBitmap(rs, outBitmap);

//Set the radius of the blur

//Perform the Renderscript

//Copy the final bitmap created by the out Allocation to the outBitmap

//recycle the original bitmap

//After finishing everything, we destroy the Renderscript.

return outBitmap;


And...voilà! Blurred bitmap! :-)

Remember that to run the previous code you need minimum API 17 (4.2.2).

Here's a Gist of this method:

If you want to discover more about Intrinsics, check out this post on Android Developers Blog:

If you're interested in know more about Renderscript, check out these links:

#gde   #android   #article    #ProTip

[Advertising]Faster Thinking - Speed up your brain

Faster Thinking Game

sentiment_satisfied Emoticon