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

 更新时间:2017年09月11日 14:16:06   作者:燊在锦官城_  
本篇文章主要介绍了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调试神器stetho使用详解和改造

    Android调试神器stetho使用详解和改造

    今天小编就为大家分享一篇关于Android调试神器stetho使用详解和改造,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-02-02
  • Android设计模式之Builder模式详解

    Android设计模式之Builder模式详解

    这篇文章主要为大家详细介绍了Android设计模式之Builder模式,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-08-08
  • android 判断横竖屏问题的详解

    android 判断横竖屏问题的详解

    本篇文章是对android中如何判断横竖屏的方法进行了详细的分析介绍,需要的朋友参考下
    2013-06-06
  • Android Studio打包APK文件具体实现步骤解析

    Android Studio打包APK文件具体实现步骤解析

    这篇文章主要介绍了Android Studio打包APK文件具体实现步骤解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-11-11
  • Android实现三角形气泡效果方式汇总

    Android实现三角形气泡效果方式汇总

    这篇文章主要介绍了Android实现三角形气泡效果方式汇总,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-03-03
  • Android中SwipeBack实现右滑返回效果

    Android中SwipeBack实现右滑返回效果

    这篇文章主要介绍了Android中SwipeBack实现右滑返回效果的相关资料,需要的朋友可以参考下
    2016-02-02
  • android 添加按(power键)电源键结束通话(挂断电话)

    android 添加按(power键)电源键结束通话(挂断电话)

    首先我们发现现在我们所用的android智能手机大部分都有当你在打电话时按power键来挂断电话,一般都是在设置中
    2013-01-01
  • Android中实现视差滚动示例介绍

    Android中实现视差滚动示例介绍

    大家好,本篇文章主要讲的是Android中实现视差滚动示例介绍,感兴趣的同学赶快来看一看吧,对你有帮助的话记得收藏一下,方便下次浏览
    2021-12-12
  • Android本地实现搜索历史记录

    Android本地实现搜索历史记录

    这篇文章主要为大家详细介绍了Android本地实现搜索历史记录,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-09-09
  • Android判断程序是否第一次启动

    Android判断程序是否第一次启动

    这篇文章主要为大家详细介绍了Android判断程序是否第一次启动的相关代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-03-03

最新评论