Android中内存高效的图像调整大小

Sio*_*e21 14 android image-manipulation bitmap

我正在尝试将从相机中检索到的图像(大约5-8百万像素)缩小到一个较小的尺寸(最大为1024x768).我尝试了以下代码,但我一直得到一个OutOfMemoryError.

Bitmap image = BitmapFactory.decodeStream(this.image, null, opt);
int imgWidth = image.getWidth();
int imgHeight = image.getHeight();

// Constrain to given size but keep aspect ratio
float scaleFactor = Math.min(((float) width) / imgWidth, ((float) height) / imgHeight);

Matrix scale = new Matrix();
scale.postScale(scaleFactor, scaleFactor);
final Bitmap scaledImage = Bitmap.createBitmap(image, 0, 0, imgWidth, imgHeight, scale, false);

image.recycle();
Run Code Online (Sandbox Code Playgroud)

看起来OOM发生在createBitmap.是否有更高效的内存方式?也许某些东西不需要我将整个原件加载到内存中?

Ebo*_*ike 16

使用BitmapFactory解码位图时,传入BitmapFactory.Options对象并指定inSampleSize.这是解码图像时节省内存的最佳方法.

这是一个示例代码将图像加载到Bitmap对象时奇怪的内存不足问题