
Android有效的治疗方法Bitmap,减少内存
照片可能有不同的大小。
在很多情况下,大小。比如,我们的Camera应用,我们所拍的照片的大小远大于屏幕显示的大小
假如你的应用被限制了内存使用,显而易见,你会选择载入一个低分辨率的图片。这张低分辨率的图片应该匹配屏幕的尺寸。更高分辨率的图像没有提供不论什么可见的优点,但仍占用宝贵的内存。并且因为额外的动态缩放。会带来额外的性能开销。
本篇文章教你通过载入一个小尺寸的图片样本,来修饰一张大图,而且没有超过应用的内存限制。
原文地址http://wear.techbrood.com/training/displaying-bitmaps/load-bitmap.html
获取图片的类型尺寸
每种解码方法都有一些标识位,你能够通过配置BitmapFactory.Options这些标识位来实现。设置inJustDecodeBounds的属性为true的时候,我们解码的时候不分配内存。返回的Bitmap为null,可是我们设置了outWidth,outHeight和outMimeType。这样的技术能够预先获取到Bitmap的大小数据和类型数据。
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), R.id.myimage, options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
String imageType = options.outMimeType;
为了避免java.lang.OutOfMemory
exceptions,在解码图片之前。预先检查Bitmap的大小,除非你有绝对的把握你的bitmap有合适的大小,而且在内存大小限制范围之内。
载入缩放的图片到内存
- 预计载入整个图像所占用的内存
- 你能够接收的内存使用量和你程序能够使用的内存
- 你放该图片的ImageView的尺寸或者其它UI组件的尺寸
- 屏幕的大小
比如。我们不值得将大小为1024x768 pixel的图片放到128*96 pixel的缩略图控件(ImageVIew)里面。
比如,我们想把一张2048*1536的图片解码为仅仅有1/4大小的图片512*384,载入到内存里卖年仅仅有0.75MB的大小,远远小宇原图12MB的大小(使用ARGB_8888通道的图片)。
这里有一种计算样本图片的方法。依据目标图片的宽度和高度width和height:
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { final int halfHeight = height / 2;
final int halfWidth = width / 2; // Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
} return inSampleSize;
}
Note: A power of two value is calculated because the decoder uses a final value by rounding down to the nearest power of two, as per the inSampleSize documentation.
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) { // First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options); // Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
这样的方法能够帮助我们轻松有效的载入一张100*100的缩略图片:
mImageView.setImageBitmap(
decodeSampledBitmapFromResource(getResources(), R.id.myimage, 100, 100));
BitmapFactory.decode*
asneed。