Skip to content

Instantly share code, notes, and snippets.

@Petrakeas
Last active February 17, 2021 06:57
Show Gist options
  • Save Petrakeas/a447c21452bebc40ee17d089b512d59e to your computer and use it in GitHub Desktop.
Save Petrakeas/a447c21452bebc40ee17d089b512d59e to your computer and use it in GitHub Desktop.
A method that uses RenderScript to downscale an image without aliasing.
public static Bitmap resizeBitmap2(RenderScript rs, Bitmap src, int dstWidth) {
Bitmap.Config bitmapConfig = src.getConfig();
int srcWidth = src.getWidth();
int srcHeight = src.getHeight();
float srcAspectRatio = (float) srcWidth / srcHeight;
int dstHeight = (int) (dstWidth / srcAspectRatio);
float resizeRatio = (float) srcWidth / dstWidth;
/* Calculate gaussian's radius */
float sigma = resizeRatio / (float) Math.PI;
// https://android.googlesource.com/platform/frameworks/rs/+/master/cpu_ref/rsCpuIntrinsicBlur.cpp
float radius = 2.5f * sigma - 1.5f;
radius = Math.min(25, Math.max(0.0001f, radius));
/* Gaussian filter */
Allocation tmpIn = Allocation.createFromBitmap(rs, src);
Allocation tmpFiltered = Allocation.createTyped(rs, tmpIn.getType());
ScriptIntrinsicBlur blurInstrinsic = ScriptIntrinsicBlur.create(rs, tmpIn.getElement());
blurInstrinsic.setRadius(radius);
blurInstrinsic.setInput(tmpIn);
blurInstrinsic.forEach(tmpFiltered);
tmpIn.destroy();
blurInstrinsic.destroy();
/* Resize */
Bitmap dst = Bitmap.createBitmap(dstWidth, dstHeight, bitmapConfig);
Type t = Type.createXY(rs, tmpFiltered.getElement(), dstWidth, dstHeight);
Allocation tmpOut = Allocation.createTyped(rs, t);
ScriptIntrinsicResize resizeIntrinsic = ScriptIntrinsicResize.create(rs);
resizeIntrinsic.setInput(tmpFiltered);
resizeIntrinsic.forEach_bicubic(tmpOut);
tmpOut.copyTo(dst);
tmpFiltered.destroy();
tmpOut.destroy();
resizeIntrinsic.destroy();
return dst;
}
@Petrakeas
Copy link
Author

Petrakeas commented Nov 13, 2017

The method is mentioned in this article.

@kenumir
Copy link

kenumir commented Feb 17, 2021

I have problem with this resize metod. One user reported that graphics are not fully loaded (screen: https://kenumir.pl/tests/resize-problem.png) - anyone have same issue?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment