1.查看当前应用程序可用的最大内存
int maxMemory = (int)(Runtime.getRuntime().maxMemory() / 1024);
Log.d("TAG", "Max memoryis " + maxMemory + "KB");
2.获取图片的宽和高, 获取的过程中不会为图片分配内存, 这样就不会有内存溢出
BitmapFactory.Options options = newBitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(),R.id.myimage, options);
int imageHeight =options.outHeight;
int imageWidth = options.outWidth;
String imageType =options.outMimeType;
3.预估
预估一下加载整张图片所需占用的内存。
为了加载这一张图片你所愿意提供多少内存。
用于展示这张图片的控件的实际大小。
当前设备的屏幕尺寸和分辨率。
4.根据想要的宽和高, 来计算压缩比
(1)如下方法:实际是计算原图片和目标图标的宽高比
public static intcalculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// 源图片的高度和宽度
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width >reqWidth) {
// 计算出实际宽高和目标宽高的比率
final int heightRatio = Math.round((float) height / (float)reqHeight);
final int widthRatio = Math.round((float) width / (float)reqWidth);
// 选择宽和高中最小的比率作为inSampleSize的值,这样可以保证最终图片的宽和高
// 一定都会大于等于目标的宽和高。
inSampleSize = heightRatio < widthRatio ? heightRatio :widthRatio;
}
return inSampleSize;
}
(2)获取压缩后的bitmap
public static BitmapdecodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// 第一次解析将inJustDecodeBounds设置为true,来获取图片大小
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// 调用上面定义的方法计算inSampleSize值
options.inSampleSize = calculateInSampleSize(options, reqWidth,reqHeight);
// 使用获取到的inSampleSize值再次解析图片
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
(3)调用方法:
mImageView.setImageBitmap(
decodeSampledBitmapFromResource(getResources(),R.id.myimage, 100, 100));
5.还有一种方法, 加载大图不压缩, 就是应用BitmapRegionDecoder, 他可以
BitmapRegionDecoderbitmapRegionDecoder =
BitmapRegionDecoder.newInstance(inputStream,false);
上述解决了传入我们需要处理的图片,那么接下来就是显示指定的区域。
bitmapRegionDecoder.decodeRegion(rect,options);
显示图片的制定矩形区域内容