RenderScript is especially useful for applications performing image processing, computational photography, or computer vision.
Let's see how you can use Renderscript to effectively blur an image.
Blurred image |
Integrating Renderscript with Gradle
To add the Renderscript support library to your Android Studio project just add the following lines to build.gradle (module: app).android {
...
defaultConfig {
renderscriptTargetApi 19
renderscriptSupportModeEnabled true
}
...
}
Code to blur the image
Now create the utility class BlurBuilder that uses RenderScript to blur the image:/*
* Copyright (c) - Software developed by iClaude.
*/
package com.flingsoftware.personalbudget.utilita;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.v8.renderscript.Allocation;
import android.support.v8.renderscript.Element;
import android.support.v8.renderscript.RenderScript;
import android.support.v8.renderscript.ScriptIntrinsicBlur;
/**
* This class is used to blur a Bitmap.
* The static method blur takes a Bitmap as input e returns a blurred version of if.
*/
public class BlurBuilder {
private static final float BITMAP_SCALE = 0.4f;
private static final float BLUR_RADIUS = 7.5f;
public static Bitmap blur(Context context, Bitmap image) {
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(inputBitmap);
RenderScript rs = RenderScript.create(context);
ScriptIntrinsicBlur theIntrinsic = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap);
Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap);
theIntrinsic.setRadius(BLUR_RADIUS);
theIntrinsic.setInput(tmpIn);
theIntrinsic.forEach(tmpOut);
tmpOut.copyTo(outputBitmap);
return outputBitmap;
}
}
As you can see the class exposes a static method, "blur", that takes the original Bitmap as a parameter and returns the blurred version of the image.
You can adjust the constants BITMAP_SCALE and BLUR_RADIUS to control the amount of blurriness.
Blurring the image
Now, if you have a Bitmap you can blur it using the following code (remeber to do this in a separate thread to avoid locking the UI):Bitmap origBitmap = ...
Bitmap blurredBitmap = BlurBuilder.blur(mContext, origBitmap);
myImageView.setImageBitmap(blurredBitmap );
blog was interesting
ReplyDeletehttp://programersglobal.com/
android training in thrissur
ReplyDeletehttp://programers.in/
Hi! This is kind of off topic but I need some help from an established blog. Is it hard to set up your own blog? I'm not very techincal but I can figure things out pretty fast. I'm thinking about making my own but I'm not sure where to start. Do you have any ideas or suggestions? Many thanks. apple reperatur berlin
ReplyDelete