aletede91 aletede91 - 3 months ago 25
Android Question

How to blur imageview in android

I have an imageview and i set Image Resources programmatically like this:

int resourceId = getResources().getIdentifier("imagename", "drawable", "mypackage");
imgLock.setImageResource(resourceId);


Is there any easy way to show my ImageView with blurry image?

Answer
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;



Bitmap blurred = blurRenderScript(this,yourBitmap, 25);
//second parametre is radius
yourImageView.setImageBitmap(blurred); 


 @SuppressLint("NewApi")
        public static Bitmap blurRenderScript(Context context,Bitmap smallBitmap, int radius) {
        try {
                smallBitmap = RGB565toARGB888(smallBitmap);
            } catch (Exception e) {
                e.printStackTrace();
            }

            Bitmap bitmap = Bitmap.createBitmap(
                    smallBitmap.getWidth(), smallBitmap.getHeight(),
                    Bitmap.Config.ARGB_8888);

            RenderScript renderScript = RenderScript.create(context);

            Allocation blurInput = Allocation.createFromBitmap(renderScript, smallBitmap);
            Allocation blurOutput = Allocation.createFromBitmap(renderScript, bitmap);

            ScriptIntrinsicBlur blur = ScriptIntrinsicBlur.create(renderScript,
                    Element.U8_4(renderScript));
            blur.setInput(blurInput);
            blur.setRadius(radius); // radius must be 0 < r <= 25
            blur.forEach(blurOutput);

            blurOutput.copyTo(bitmap);
            renderScript.destroy();

            return bitmap;

        }

        private static Bitmap RGB565toARGB888(Bitmap img) throws Exception {
            int numPixels = img.getWidth() * img.getHeight();
            int[] pixels = new int[numPixels];

            //Get JPEG pixels.  Each int is the color values for one pixel.
            img.getPixels(pixels, 0, img.getWidth(), 0, 0, img.getWidth(), img.getHeight());

            //Create a Bitmap of the appropriate format.
            Bitmap result = Bitmap.createBitmap(img.getWidth(), img.getHeight(), Bitmap.Config.ARGB_8888);

            //Set RGB pixels.
            result.setPixels(pixels, 0, result.getWidth(), 0, 0, result.getWidth(), result.getHeight());
            return result;
        }