全网整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:400-708-3566

Android 图片处理避免出现oom的方法详解

1. 通过设置采样率压缩

res资源图片压缩 decodeResource

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

uri图片压缩 decodeStream

  public Bitmap decodeSampledBitmapFromUri(Uri uri, int reqWidth, int reqHeight) {
    Bitmap bitmap = null;
    try {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), null, options);
    options.inSampleSize = BitmapUtils.calculateInSampleSize(options,
        UtilUnitConversion.dip2px(MyApplication.mContext, reqWidth), UtilUnitConversion.dip2px(MyApplication.mContext, reqHeight));
    options.inJustDecodeBounds = false;

    bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), null, options);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return bitmap;
  }

本地File url图片压缩

  public static Bitmap getloadlBitmap(String load_url, int width, int height) {
    Bitmap bitmap = null;
    if (!UtilText.isEmpty(load_url)) {
      File file = new File(load_url);
      if (file.exists()) {
        FileInputStream fs = null;
        try {
          fs = new FileInputStream(file);
        } catch (FileNotFoundException e) {
          e.printStackTrace();
        }
        if (null != fs) {
          try {
            BitmapFactory.Options opts = new BitmapFactory.Options();
            opts.inJustDecodeBounds = true;
            BitmapFactory.decodeFileDescriptor(fs.getFD(), null, opts);
            opts.inDither = false;
            opts.inPurgeable = true;
            opts.inInputShareable = true;
            opts.inTempStorage = new byte[32 * 1024];
            opts.inSampleSize = BitmapUtils.calculateInSampleSize(opts,
                UtilUnitConversion.dip2px(MyApplication.mContext, width), UtilUnitConversion.dip2px(MyApplication.mContext, height));
            opts.inJustDecodeBounds = false;

            bitmap = BitmapFactory.decodeFileDescriptor(fs.getFD(),
                null, opts);
          } catch (IOException e) {
            e.printStackTrace();
          } finally {
            if (null != fs) {
              try {
                fs.close();
              } catch (IOException e) {
                e.printStackTrace();
              }
            }
          }
        }
      }
    }
    return bitmap;
  }

根据显示的图片大小进行SampleSize的计算

public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
    if (reqWidth == 0 || reqHeight == 0) {
      return 1;
    }

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

调用方式:

复制代码 代码如下:
mImageView.setImageBitmap(decodeSampledBitmapFromResource(getResources(), R.id.myImage, 100, 100))

Bitmap bitmap = decodeSampledBitmapFromUri(cropFileUri);
UtilBitmap.setImageBitmap(mContext, mImage,
        UtilBitmap.getloadlBitmap(url, 100, 100),
        R.drawable.ic_login_head, true);

2. 质量压缩:指定图片缩小到xkb以下

  // 压缩到100kb以下
  int maxSize = 100 * 1024;
  public static Bitmap getBitmapByte(Bitmap oriBitmap, int maxSize) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    oriBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);

    byte[] fileBytes = out.toByteArray();

    int be = (maxSize * 100) / fileBytes.length;

    if (be > 100) {
      be = 100;
    }
    out.reset();
    oriBitmap.compress(Bitmap.CompressFormat.JPEG, be, out);
    return oriBitmap;
  }

3. 单纯获取图片宽高避免oom的办法

itmapFactory.Options这个类,有一个字段叫做 inJustDecodeBounds 。SDK中对这个成员的说明是这样的:
If set to true, the decoder will return null (no bitmap), but the out...

也就是说,如果我们把它设为true,那么BitmapFactory.decodeFile(String path, Options opt)并不会真的返回一个Bitmap给你,它仅仅会把它的宽,高取回来给你,这样就不会占用太多的内存,也就不会那么频繁的发生OOM了。

  /**
   * 根据res获取Options,来获取宽高outWidth和options.outHeight
   * @param res
   * @param resId
   * @return
   */
  public static BitmapFactory.Options decodeOptionsFromResource(Resources res, int resId) {
    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);
    return options;
  }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


# android  # 图片处理oom  # 处理oom  # oom处理  # Android之OOM异常解决案例讲解  # Android 加载大图及多图避免程序出现OOM(OutOfMemory)异常  # 解决Android解析图片的OOM问题的方法!!!  # Android LeakCanary检测内存泄露原理  # Android中LeakCanary检测内存泄漏的方法  # Android内存泄漏排查利器LeakCanary  # 使用Android Studio检测内存泄露(LeakCanary)  # Android 进阶实现性能优化之OOM与Leakcanary详解原理  # 给你  # 太多  # 也就  # 是这样  # 设为  # 把它  # 会把  # 中对  # 大家多多  # 有一个  # 也就是说  # 采样率  # dip2px  # UtilUnitConversion  # BitmapUtils  # Exception  # catch  # mContext  # MyApplication  # openInputStream 


相关文章: 小建面朝正北,A点实际方位是否存在偏差?  Python多线程使用规范_线程安全解析【教程】  ppt在线制作免费网站推荐,有什么下载免费的ppt模板网站?  活动邀请函制作网站有哪些,活动邀请函文案?  GML (Geography Markup Language)是什么,它如何用XML来表示地理空间信息?  如何快速搭建高效服务器建站系统?  如何在云主机上快速搭建网站?  如何通过多用户协作模板快速搭建高效企业网站?  弹幕视频网站制作教程下载,弹幕视频网站是什么意思?  婚礼视频制作网站,学习*后期制作的网站有哪些?  成都网站制作价格表,现在成都广电的单独网络宽带有多少的,资费是什么情况呢?  如何通过IIS搭建网站并配置访问权限?  如何通过可视化优化提升建站效果?  视频网站制作教程,怎么样制作优酷网的小视频?  如何在宝塔面板中创建新站点?  建站之星微信建站一键生成小程序+多端营销系统  成都响应式网站开发,dw怎么把手机适应页面变成网页?  购物网站制作公司有哪些,哪个购物网站比较好?  建站之星备案是否影响网站上线时间?  如何快速启动建站代理加盟业务?  学校建站服务器如何选型才能满足性能需求?  湖南网站制作公司,湖南上善若水科技有限公司做什么的?  小米网站链接制作教程,请问miui新增网页链接调用服务有什么用啊?  如何通过FTP服务器快速搭建网站?  建站之星如何助力企业快速打造五合一网站?  网站制作公司哪里好做,成都网站制作公司哪家做得比较好,更正规?  成都网站制作公司哪家好,四川省职工服务网是做什么用?  正规网站制作公司有哪些,目前国内哪家网页网站制作设计公司比较专业靠谱?口碑好?  北京网站制作网页,网站升级改版需要多久?  深圳网站制作平台,深圳市做网站好的公司有哪些?  免费制作海报的网站,哪位做平面的朋友告诉我用什么软件做海报比较好?ps还是cd还是ai这几个软件我都会些我是做网页的?  如何基于PHP生成高效IDC网络公司建站源码?  厦门模型网站设计制作公司,厦门航空飞机模型掉色怎么办?  微网站制作教程,不会写代码,不会编程,怎么样建自己的网站?  香港服务器选型指南:免备案配置与高效建站方案解析  齐河建站公司:营销型网站建设与SEO优化双核驱动策略  高防网站服务器:DDoS防御与BGP线路的AI智能防护方案  如何在云主机快速搭建网站站点?  广州网站设计制作一条龙,广州巨网网络科技有限公司是干什么的?  全景视频制作网站有哪些,全景图怎么做成网页?  合肥制作网站的公司有哪些,合肥聚美网络科技有限公司介绍?  网站视频怎么制作,哪个网站可以免费收看好莱坞经典大片?  如何在橙子建站中快速调整背景颜色?  建站主机选购指南:核心配置优化与品牌推荐方案  制作网站的网址是什么,请问后缀为.com和.com.cn还有.cn的这三种网站是分别是什么类型的网站?  小说建站VPS选用指南:性能对比、配置优化与建站方案解析  如何通过二级域名建站提升品牌影响力?  ,制作一个手机app网站要多少钱?  电商网站制作公司有哪些,1688网是什么意思?  如何选择高性价比服务器搭建个人网站? 

您的项目需求

*请认真填写需求信息,我们会在24小时内与您取得联系。