前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Android 图片处理避免出现oom的方法详解

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

作者头像
砸漏
发布2020-10-22 11:04:54
9770
发布2020-10-22 11:04:54
举报
文章被收录于专栏:恩蓝脚本

1. 通过设置采样率压缩

res资源图片压缩 decodeResource

代码语言:javascript
复制
  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

代码语言:javascript
复制
  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图片压缩

代码语言:javascript
复制
  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的计算

代码语言:javascript
复制
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))

代码语言:javascript
复制
Bitmap bitmap = decodeSampledBitmapFromUri(cropFileUri);
代码语言:javascript
复制
UtilBitmap.setImageBitmap(mContext, mImage,
        UtilBitmap.getloadlBitmap(url, 100, 100),
        R.drawable.ic_login_head, true);

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

代码语言:javascript
复制
  // 压缩到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了。

代码语言:javascript
复制
  /**
   * 根据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;
  }

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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-09-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
文件存储
文件存储(Cloud File Storage,CFS)为您提供安全可靠、可扩展的共享文件存储服务。文件存储可与腾讯云服务器、容器服务、批量计算等服务搭配使用,为多个计算节点提供容量和性能可弹性扩展的高性能共享存储。腾讯云文件存储的管理界面简单、易使用,可实现对现有应用的无缝集成;按实际用量付费,为您节约成本,简化 IT 运维工作。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档