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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3219672/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 09:11:59  来源:igfitidea点击:

Memory efficient image resize in Android

androidbitmapimage-manipulation

提问by Sionide21

I am trying to reduce the size of images retrieved form the camera (so ~5-8 mega pixels) down to one a a few smaller sizes (the largest being 1024x768). I Tried the following code but I consistently get an OutOfMemoryError.

我正在尝试将从相机中检索到的图像的大小(大约 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();

It looks like the OOM happens during the createBitmap. Is there a more memory efficient way to do this? Perhaps something that doesn't require me to load the entire original into memory?

看起来 OOM 发生在createBitmap. 有没有更有效的内存方法来做到这一点?也许不需要我将整个原件加载到内存中的东西?

回答by EboMike

When you decode the bitmap with the BitmapFactory, pass in a BitmapFactory.Options object and specify inSampleSize. This is the best way to save memory when decoding an image.

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

Here's a sample code Strange out of memory issue while loading an image to a Bitmap object

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

回答by Mathias Conradt

Are you taking the picture with the camera within your application? If so, you should set the picture size to a smaller one in the first place when they're being captured via android.hardware.Camera.Parameters.setPictureSize

您是否在应用程序中使用相机拍照?如果是这样,您应该在通过以下方式捕获图片时首先将图片大小设置为较小的android.hardware.Camera.Parameters.setPictureSize

回答by toidiu

Here is a similar question that I answered and show how to go about dynamically loading the proper image size.

这是我回答的一个类似问题,并展示了如何动态加载正确的图像大小。

out of memory exception + analyzing hprof file dump

内存不足异常 + 分析 hprof 文件转储