ImageSmoothing in Android
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
import android.widget.ImageView;
public class ImageSmoothing extends AsyncTask {
private Bitmap bitmap;
private Context context;
private ImageView imageView;
public ImageSmoothing(Bitmap bitmap, Context context, ImageView imageView) {
this.bitmap = bitmap;
this.context = context;
this.imageView = imageView;
}
@Override
protected Bitmap doInBackground(Void... voids) {
Bitmap inputBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
Bitmap outputBitmap = Bitmap.createBitmap(inputBitmap.getWidth(), inputBitmap.getHeight(), Bitmap.Config.ARGB_8888);
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(25f);
theIntrinsic.setInput(tmpIn);
theIntrinsic.forEach(tmpOut);
tmpOut.copyTo(outputBitmap);
return outputBitmap;
}
@Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
}
In this class, you can pass the Bitmap image that needs to be smoothed, the context of the current activity, and the ImageView where the smoothed image needs to be displayed. You can call this class using the following code:
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image_to_smooth);
ImageView imageView = findViewById(R.id.smoothed_image);
new ImageSmoothing(bitmap, this, imageView).execute();
This will start the image smoothing process in the background and set the smoothed image in the ImageView once it's done. Note that the smoothing process may take some time, so it's important to run it in the background using an AsyncTask.