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


更多相关文章

  1. 【Android】第5章(8) 图片库(Galery)
  2. 【Android游戏开发十六】Android(安卓)Gesture之【触摸屏手势识
  3. 【Android】本地图片选择(打开媒体库,选择图片)
  4. Android枚举类引用实例
  5. Android(安卓)画顶部带锯齿的长方形
  6. 手机主流适配
  7. android 虚拟机设置屏幕尺寸
  8. Android开发之Ruby实现Android自动化屏幕适配
  9. Android(安卓)重要基本开发规范

随机推荐

  1. android 检测sqlite数据表和表中字段(列)是
  2. android中动画学习
  3. Android自学之--短信发送器
  4. android之res/values、国际化
  5. 【工具类】Android自定义Dialog
  6. Android 获取mac地址方法
  7. OOM
  8. Android时间对话框
  9. android canvas中translate函数的使用
  10. 如何修改Android设备MTP name