How to Blur Image in Android

thumb-how-to-blur-image-in-android

28th February, 2020

Image Blurring is a useful tool in Image Processing. You can highlight and focus the image using the blur effect. Android RenderScript helps you to do this. This example shows how to create image blur effect.

Step 1: Create New Project

Create a new project in Android Studio from File ⇒ New Project and select Empty Activity from the templates.

Open your app level build.gradle and enable View Binding.

Project ⇒ app ⇒ build.gradle

apply plugin: 'com.android.application'

android {
    viewBinding {
        enabled = true
    }
    /*other stuff*/
}

Step 2: Enable RenderScript Support

You need to configure the build.gradle to enable RenderScript in your project. To do this add the following code.

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28

    viewBinding {
        enabled = true
    }

    defaultConfig {
        applicationId "com.codestringz.blurimageexample"
        minSdkVersion 19
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"

        //---RenderScript---//
        renderscriptTargetApi 19
        renderscriptSupportModeEnabled true
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'androidx.appcompat:appcompat:1.1.0'
}

Step 3: Using RenderScript

Create an Util class and add a method that will help you to create blur effect.

package com.codestringz.blurimageexample;

import android.content.Context;
import android.graphics.Bitmap;

import androidx.renderscript.Allocation;
import androidx.renderscript.Element;
import androidx.renderscript.RenderScript;
import androidx.renderscript.ScriptIntrinsicBlur;

public class MyBlurBuilder
{
    public static Bitmap applyBlur(Context pContext, Bitmap pSrcBitmap, float pBlurRadius)
    {
        if (pSrcBitmap != null)
        {
            Bitmap copyBitmap = pSrcBitmap.copy(Bitmap.Config.ARGB_8888, true);
            Bitmap outputBitmap = Bitmap.createBitmap(copyBitmap);

            RenderScript renderScript = RenderScript.create(pContext);
            ScriptIntrinsicBlur scriptIntrinsicBlur = ScriptIntrinsicBlur.create(renderScript, Element.U8_4(renderScript));

            Allocation allocationIn = Allocation.createFromBitmap(renderScript, pSrcBitmap);
            Allocation allocationOut = Allocation.createFromBitmap(renderScript, outputBitmap);

            scriptIntrinsicBlur.setRadius(pBlurRadius);
            scriptIntrinsicBlur.setInput(allocationIn);
            scriptIntrinsicBlur.forEach(allocationOut);

            allocationOut.copyTo(outputBitmap);

            return outputBitmap;
        }
        else
        {
            return null;
        }
    }
}

Now open the activity and apply blur to the Image.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="15dp"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/pets_img"
        tools:ignore="ContentDescription" />

    <SeekBar
        android:id="@+id/blurSeekBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:max="25"
        android:progress="16"/>

    <Button
        android:id="@+id/blurButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:text="Apply Blur" />

</LinearLayout>
package com.codestringz.blurimageexample;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.codestringz.blurimageexample.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity
{
    private ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        View view = binding.getRoot();
        setContentView(view);

        binding.blurButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                createBlurImage();
            }
        });
    }

    private void createBlurImage()
    {
        //Get seekBar progress
        int blurRadius = binding.blurSeekBar.getProgress();

        /*
         * Note: 0 < blur radius <= 25
         * */
        if (blurRadius == 0)
        {
            Toast.makeText(this, "Please increase blurriness radius", Toast.LENGTH_SHORT).show();
            return;
        }

        //Create bitmap (Note: Use Image Loading Library like Glide)
        Bitmap srcBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.pets_img);

        //Blurring
        Bitmap blurredBitmap = MyBlurBuilder.applyBlur(this, srcBitmap, blurRadius);

        if (blurredBitmap != null)
        {
            //Set Blurred bitmap to imageView
            binding.imageView.setImageBitmap(blurredBitmap);
        }
    }
}

Happy coding!

Leave a Reply