20

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?

aletede91
  • 1,137
  • 2
  • 16
  • 30

13 Answers13

17

You can use glide transformations https://github.com/wasabeef/glide-transformations you can blur the image with one line of code

Glide.with(this).load(R.drawable.demo)
    .bitmapTransform(new BlurTransformation(context))
    .into((ImageView) findViewById(R.id.image));
user3096729
  • 193
  • 1
  • 4
7
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;
}
Marlon
  • 1,839
  • 2
  • 19
  • 42
Lins Louis
  • 2,393
  • 2
  • 25
  • 30
  • 1
    This works on API level 17 and above, for lower API levels there is a support library [`android.support.v8.renderscript.ScriptIntrinsicBlur `](https://developer.android.com/reference/android/support/v8/renderscript/ScriptIntrinsicBlur.html). – gregn3 Sep 13 '17 at 14:20
  • 1
    Nice. No external libraries. Simple and short solution. Thank you. – Sermilion Feb 09 '19 at 00:57
  • 1
    After reading these instructions (https://github.com/xamarin/docs-archive/tree/master/Recipes/android/other_ux/drawing/blur_an_image_with_renderscript), it seemed that is a good practice to place both methods (blurRenderScript() and RGB565toARGB888()) inside an `AsyncTask`. – Aliton Oliveira Dec 21 '19 at 21:54
  • RenderScript is deprecarted... – Crisic Jul 24 '23 at 09:37
3

There are many libraries are available you can use any of these. I prefer Blurry library for it. it is very simple and optimized.

dependency:

 dependencies {
    compile 'jp.wasabeef:blurry:4.x.x'
}

Functions

  • Blurry.with(context).radius(25).sampling(2).onto(rootView)
  • // from View Blurry.with(context).capture(view).into(imageView)
  • // from Bitmap Blurry.with(context).from(bitmap).into(imageView)

Blur Options

  • Radius
  • Down Sampling
  • Color Filter
  • Asynchronous Support
  • Animation (Overlay Only)
Blurry.with(context)
  .radius(10)
  .sampling(8)
  .color(Color.argb(66, 255, 255, 0))
  .async()
  .animate(500)
  .onto(rootView);

Get a bitmap directly

// Sync
val bitmap = Blurry.with(this)
  .radius(10)
  .sampling(8)
  .capture(findViewById(R.id.right_bottom)).get()
imageView.setImageDrawable(BitmapDrawable(resources, bitmap))

// Async
Blurry.with(this)
  .radius(25)
  .sampling(4)
  .color(Color.argb(66, 255, 255, 0))
  .capture(findViewById(R.id.left_bottom))
  .getAsync {
    imageView.setImageDrawable(BitmapDrawable(resources, it))
  }
Hemant Patel
  • 125
  • 1
  • 4
2

Originally answered here

Android 12 Preview 1 comes with built-in blur feature. We need not depend on external library now. Here is the code

imageView.setRenderEffect(
        RenderEffect.createBlurEffect(
            20.0f, 20.0f, SHADER_TITLE_MODE
        )
)
Ramakrishna Joshi
  • 1,442
  • 17
  • 22
1
private Bitmap CreateBlurredImage (int radius)
{
   // Load a clean bitmap and work from that
    Bitmap originalBitmap=
    BitmapFactory.DecodeResource(Resources,Resource.Drawable.dog_and_monkeys);

// 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.MipmapFull, AllocationUsage.Script);
Allocation output = Allocation.CreateTyped (rs, input.Type);

// 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;

}

protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);

SetContentView (Resource.Layout.Main);
_imageView = FindViewById<ImageView> (Resource.Id.originalImageView);

_seekbar = FindViewById<SeekBar> (Resource.Id.seekBar1);
_seekbar.StopTrackingTouch += BlurImageHandler;

}

private void BlurImageHandler (object sender, SeekBar.StopTrackingTouchEventArgs e)
{
int radius = e.SeekBar.Progress;
if (radius == 0) {
    // We don't want to blur, so just load the un-altered image.
    _imageView.SetImageResource (Resource.Drawable.dog_and_monkeys);
} else {
    DisplayBlurredImage (radius);
}

}

private void DisplayBlurredImage (int radius)
{
_seekbar.StopTrackingTouch -= BlurImageHandler;
_seekbar.Enabled = false;

ShowIndeterminateProgressDialog ();

Task.Factory.StartNew (() => {
    Bitmap bmp = CreateBlurredImage (radius);
    return bmp;
})
.ContinueWith (task => {
    Bitmap bmp = task.Result;
    _imageView.SetImageBitmap (bmp);
    _seekbar.StopTrackingTouch += BlurImageHandler;
    _seekbar.Enabled = true;
    DismissIndeterminateProgressDialog ();
}, TaskScheduler.FromCurrentSynchronizationContext ());

}

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent">
    <SeekBar
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/seekBar1"
            android:max="25" />
    <ImageView
            android:src="@drawable/dog_and_monkeys"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:id="@+id/originalImageView" />
</LinearLayout>

click here deatiled code example

wadali
  • 2,221
  • 1
  • 20
  • 38
1

Just simply use this library https://github.com/ChathuraHettiarachchi/BlurIM , I was having problem with BlurTransformation class had errors thats why couldn't use Glide transformation but this works fine.

BlurImage.withContext(this)
     .blurFromResource(R.drawable.YOUR_RESOURCE)
     .into(imageView);
Petar Ceho
  • 114
  • 2
  • 7
0

You can use RenderScript to accomblish that as explained here or you can use the stackblur library to make a blurring effect in your image.

Usage of the stackblur library:

int resourceId = getResources().getIdentifier("imagename", "drawable", "mypackage");
// get bitmap from resource id
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resourceId);
StackBlurManager stackBlurManager = new StackBlurManager(bitmap);
// process the image using a certain radius
stackBlurManager.process(progress*4);
// obtain the image and load it into an ImageView or any other component
imgLock.setImageBitmap(stackBlurManager.returnBlurredImage());
Community
  • 1
  • 1
Ahmed Hegazy
  • 12,395
  • 5
  • 41
  • 64
  • When I import StackBlur project eclipse give me this error `Unable to resolve sdk.buildtools property value '18.1.0' - Unknown Android Build Tools Problem`. How can I solve? – aletede91 Jan 09 '15 at 00:20
  • you can install it from the Android SDK Manager. In `Tools` section you will find Android Build Tools just install `18.1.0` version. – Ahmed Hegazy Jan 09 '15 at 00:22
  • I installed but now I have new error `RenderScript support mode requires Build-Tools 19.0.3 or later.` – aletede91 Jan 09 '15 at 00:27
  • seems as an issue in the lib https://github.com/kikoso/android-stackblur/issues/22. You should change the Android Build Tools to the latest version. – Ahmed Hegazy Jan 09 '15 at 00:34
0

There's the library that can use RenderScript so a blurring is blazingly fast and super easy to use:

<ru.egslava.blurredview.BlurredImageView
    ...
    android:src="@drawable/..."
    app:radius="0.3"
    app:keepOriginal="true"
    app:downSampling="2" />
Slava
  • 1,314
  • 14
  • 28
0

Add dependencies

compile 'jp.wasabeef:fresco-processors:2.1.0'

Use following code in layout file:

<com.facebook.drawee.view.SimpleDraweeView
   android:id="@+id/imageView"
   android:layout_width="match_parent"
   android:layout_height="match_parent"/>

Use following code in your java file:

SimpleDraweeView imgView = (SimpleDraweeView) findViewById(R.id.imageView);
            ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
                    .setPostprocessor(new IterativeBoxBlurPostProcessor(20))
                    .build();
            DraweeController controller = Fresco.newDraweeControllerBuilder()
                    .setImageRequest(request)
                    .setOldController(imgView.getController())
                    .build();
            imgView.setController(controller);
Faisal Shaikh
  • 3,900
  • 5
  • 40
  • 77
0

You can also blur an ImageView by using Coil library.

image.load("http://xxx.jpg") {
  transformations(BlurTransformation(applicationContext,20f))
}
Ahmet B.
  • 1,290
  • 10
  • 20
  • While using this, it currently does not work with the latest coil version. I was using coil 2.2.2 but had to downgrade to 1.4.0 for it to work on my side. I hope they will provide blur support for the latest coil versions – Felix Kariuki Dec 18 '22 at 15:07
0

Late here but I got an error trying to use bitmaptransfrom directly after load. If you are facing the same, use:

Glide.with(mContext).load(drawable).apply(RequestOptions.bitmapTransform(new BlurTransformation())).into(imageView);
Aravind Varma
  • 38
  • 1
  • 6
-1

There are different ways to make view blur in android, But i found the easiest and fastest way to make views blur using Fresco library.

Add following dependency inside your build.gradle of your module.

   compile 'jp.wasabeef:fresco-processors:2.1.0'

And inside onCreate() of Activity.

        Fresco.initialize(this);
    setContentView(R.layout.activity_main);

    SimpleDraweeView  simpleDraweeView = (SimpleDraweeView) findViewById(R.id.sdv_image);

    //INSTANTIATE BLUR POST PROCESSOR
    Postprocessor  postprocessor = new BlurPostprocessor(this, BLUR_PRECENTAGE);

    //INSTATNTING IMAGE REQUEST USING POST PROCESSOR AS PARAMETER
    ImageRequest  imageRequest = ImageRequestBuilder.newBuilderWithSource(Uri.parse(IMAGE_URL))
            .setPostprocessor(postprocessor)
            .build();

    //INSTANTATE CONTROLLOR()
    PipelineDraweeController  controller = (PipelineDraweeController) Fresco.newDraweeControllerBuilder()
            .setImageRequest(imageRequest)
            .setOldController(simpleDraweeView.getController())
            .build();

    //LOAD BLURRED IMAGE ON SimpleDraweeView(VIEW)
    simpleDraweeView.setController(controller);

If you need complete implementation please visit this blog Fastest Image Blur in Android Using Fresco.

-3

This is simple method

set blur color with alpha

public class BlurImageView extends ImageView {
    Paint rectPaint;

  private  int blurcolor=Color.parseColor("#aeffffff");
    public BlurImageView(Context context) {
        this(context, null);

    }

    public BlurImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);

    }

    public BlurImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        rectPaint=new Paint();
        rectPaint.setAntiAlias(true);
        rectPaint.setStyle(Paint.Style.FILL);
        rectPaint.setColor(blurcolor);
        invalidate();
    }

    public void setBlurcolor(int blurcolor) {
        this.blurcolor = blurcolor;
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        Log.i("BlurImageView","canvas");

        canvas.drawRect(getLeft(),0,getRight(),getHeight(),rectPaint);
    }
}
sujith s
  • 864
  • 11
  • 20