Android中的内存高效图像调整大小 [英] Memory efficient image resize in Android

查看:26
本文介绍了Android中的内存高效图像调整大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将从相机中检索到的图像的大小(大约 5-8 兆像素)缩小到一些较小的尺寸(最大的是 1024x768).我尝试了以下代码,但我始终收到 OutOfMemoryError.

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.

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();

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

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?

推荐答案

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

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.

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

这篇关于Android中的内存高效图像调整大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆