Skip to content

Instantly share code, notes, and snippets.

@Tufan21
Last active February 15, 2017 06:15
Show Gist options
  • Save Tufan21/45a5f7299a9835c365f32ebeb9bd3ce4 to your computer and use it in GitHub Desktop.
Save Tufan21/45a5f7299a9835c365f32ebeb9bd3ce4 to your computer and use it in GitHub Desktop.
Blur Bitmap from drawable
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
Drawable splashDrawable= ContextCompat.getDrawable(mContext,R.drawable.splash_image);//get drawable from resources folder
BitmapDrawable drawable = (BitmapDrawable) splashDrawable;
Bitmap bitmap = drawable.getBitmap();
Bitmap blurred = blurRenderScript(bitmap, 15);//second parametre is radius
imageSplash.setImageBitmap(blurred);
@SuppressLint("NewApi")
private Bitmap blurRenderScript(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(mContext);
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 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment