Android 加载大图片造成OOM异常解决方法

来源:互联网 发布:条码生成器软件 编辑:程序博客网 时间:2024/05/12 17:47

Dalvik对android应用程序的最大内存有限制,而解析图片又是比较耗资源的,比如说解析一个2048*1536的位图需要12M的内存,这通常会造成OOM。


解决方案:根据设备的分辨率降低待加载的图片的质量,比如说设备分辨率为480*320,那么只需要将待加载的图片(比如:2048*1536)压缩成480*320就可以了,至于怎么压缩android SDK提供了解决方案,具体作法如下:


/** * 根据图片实际尺寸和待显示尺寸计算图片压缩比率 * @param options * @param reqWidth显示宽度 * @param reqHeight显示高度 * @return压缩比率 */public static int calculateInSampleSize(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 = heightRatio < widthRatio ? heightRatio : widthRatio;}return inSampleSize;}/** * 根据显示尺寸,获取压缩后的图片 * @param res * @param resId * @param reqWidth显示宽度 * @param reqHeight显示高度 * @return */public static Bitmap decodeSampledBitmapFromResource(Resources res,int resId, int reqWidth, int reqHeight) {final BitmapFactory.Options options = new BitmapFactory.Options();//不压缩,获取实际宽、高options.inJustDecodeBounds = true;BitmapFactory.decodeResource(res, resId, options);// 计算压缩比率options.inSampleSize = calculateInSampleSize(options, reqWidth,reqHeight);// 设置压缩选项options.inJustDecodeBounds = false;return BitmapFactory.decodeResource(res, resId, options);}


原创粉丝点击