Header Ads

Android ProTips: Blur Images Efficiently using Renderscript

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
blurScript.setRadius(25.f);


//Perform the Renderscript
blurScript.setInput(allIn);
blurScript.forEach(allOut);


//Copy the final bitmap created by the out Allocation to the outBitmap
allOut.copyTo(outBitmap);


//recycle the original bitmap
bitmap.recycle();


//After finishing everything, we destroy the Renderscript.
rs.destroy();


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:
https://gist.github.com/Mariuxtheone/903c35b4927c0df18cf8

If you want to discover more about Intrinsics, check out this post on Android Developers Blog:
http://android-developers.blogspot.it/2013/08/renderscript-intrinsics.html

If you're interested in know more about Renderscript, check out these links:
http://android-developers.blogspot.it/2011/02/introducing-renderscript.html
http://android-developers.blogspot.it/2011/03/renderscript.html

#gde   #android   #article    #ProTip

No comments:

Powered by Blogger.