Android图片缓存之Bitmap详解(一)

前言:
最近准备研究一下图片缓存框架,基于这个想法觉得还是先了解有关图片缓存的基础知识,今天重点学习一下Bitmap、BitmapFactory这两个类。 

Bitmap:
Bitmap是Android系统中的图像处理的最重要类之一。用它可以获取图像文件信息,进行图像剪切、旋转、缩放等操作,并可以指定格式保存图像文件。
 重要函数
 •public void recycle() // 回收位图占用的内存空间,把位图标记为Dead
 •public final boolean isRecycled() //判断位图内存是否已释放  
 •public final int getWidth()//获取位图的宽度 
 •public final int getHeight()//获取位图的高度
 •public final boolean isMutable()//图片是否可修改 
 •public int getScaledWidth(Canvas canvas)//获取指定密度转换后的图像的宽度 
 •public int getScaledHeight(Canvas canvas)//获取指定密度转换后的图像的高度 
 •public boolean compress(CompressFormat format, int quality, OutputStream stream)//按指定的图片格式以及画质,将图片转换为输出流。 
 format:Bitmap.CompressFormat.PNG或Bitmap.CompressFormat.JPEG 
 quality:画质,0-100.0表示最低画质压缩,100以最高画质压缩。对于PNG等无损格式的图片,会忽略此项设置。
 •public static Bitmap createBitmap(Bitmap src) //以src为原图生成不可变得新图像 
 •public static Bitmap createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter)//以src为原图,创建新的图像,指定新图像的高宽以及是否可变。 
 •public static Bitmap createBitmap(int width, int height, Config config)——创建指定格式、大小的位图 
 •public static Bitmap createBitmap(Bitmap source, int x, int y, int width, int height)以source为原图,创建新的图片,指定起始坐标以及新图像的高宽。

BitmapFactory工厂类:
Option 参数类:
 •public boolean inJustDecodeBounds//如果设置为true,不获取图片,不分配内存,但会返回图片的高度宽度信息。
 •public int inSampleSize//图片缩放的倍数
 •public int outWidth//获取图片的宽度值
 •public int outHeight//获取图片的高度值 
 •public int inDensity//用于位图的像素压缩比 
 •public int inTargetDensity//用于目标位图的像素压缩比(要生成的位图) 
 •public byte[] inTempStorage //创建临时文件,将图片存储
 •public boolean inScaled//设置为true时进行图片压缩,从inDensity到inTargetDensity
 •public boolean inDither //如果为true,解码器尝试抖动解码
 •public Bitmap.Config inPreferredConfig //设置解码器
 •public String outMimeType //设置解码图像
 •public boolean inPurgeable//当存储Pixel的内存空间在系统内存不足时是否可以被回收
 •public boolean inInputShareable //inPurgeable为true情况下才生效,是否可以共享一个InputStream
 •public boolean inPreferQualityOverSpeed  //为true则优先保证Bitmap质量其次是解码速度
 •public boolean inMutable //配置Bitmap是否可以更改,比如:在Bitmap上隔几个像素加一条线段
 •public int inScreenDensity //当前屏幕的像素密度

 工厂方法:
 •public static Bitmap decodeFile(String pathName, Options opts) //从文件读取图片 
 •public static Bitmap decodeFile(String pathName)
 •public static Bitmap decodeStream(InputStream is) //从输入流读取图片
 •public static Bitmap decodeStream(InputStream is, Rect outPadding, Options opts)
 •public static Bitmap decodeResource(Resources res, int id) //从资源文件读取图片
 •public static Bitmap decodeResource(Resources res, int id, Options opts) 
 •public static Bitmap decodeByteArray(byte[] data, int offset, int length) //从数组读取图片
 •public static Bitmap decodeByteArray(byte[] data, int offset, int length, Options opts)
 •public static Bitmap decodeFileDescriptor(FileDescriptor fd)//从文件读取文件 与decodeFile不同的是这个直接调用JNI函数进行读取 效率比较高
 •public static Bitmap decodeFileDescriptor(FileDescriptor fd, Rect outPadding, Options opts)

Bitmap.Config inPreferredConfig : 
枚举变量 (位图位数越高代表其可以存储的颜色信息越多,图像越逼真,占用内存越大)
 •public static final Bitmap.Config ALPHA_8 //代表8位Alpha位图        每个像素占用1byte内存
 •public static final Bitmap.Config ARGB_4444 //代表16位ARGB位图  每个像素占用2byte内存
 •public static final Bitmap.Config ARGB_8888 //代表32位ARGB位图  每个像素占用4byte内存
 •public static final Bitmap.Config RGB_565 //代表8位RGB位图          每个像素占用2byte内存

Android中一张图片(BitMap)占用的内存主要和以下几个因数有关:图片长度,图片宽度,单位像素占用的字节数。

一张图片(BitMap)占用的内存=图片长度*图片宽度*单位像素占用的字节数

图片读取实例:
 1.)从文件读取方式一

 /**
  * 获取缩放后的本地图片
  *
  * @param filePath 文件路径
  * @param width 宽
  * @param height 高
  * @return
  */
 public static Bitmap readBitmapFromFile(String filePath, int width, int height) {
  BitmapFactory.Options options = new BitmapFactory.Options();
  options.inJustDecodeBounds = true;
  BitmapFactory.decodeFile(filePath, options);
  float srcWidth = options.outWidth;
  float srcHeight = options.outHeight;
  int inSampleSize = 1;

  if (srcHeight > height || srcWidth > width) {
   if (srcWidth > srcHeight) {
    inSampleSize = Math.round(srcHeight / height);
   } else {
    inSampleSize = Math.round(srcWidth / width);
   }
  }

  options.inJustDecodeBounds = false;
  options.inSampleSize = inSampleSize;

  return BitmapFactory.decodeFile(filePath, options);
 }

 2.)从文件读取方式二 效率高于方式一

/**
  * 获取缩放后的本地图片
  *
  * @param filePath 文件路径
  * @param width 宽
  * @param height 高
  * @return
  */
 public static Bitmap readBitmapFromFileDescriptor(String filePath, int width, int height) {
  try {
   FileInputStream fis = new FileInputStream(filePath);
   BitmapFactory.Options options = new BitmapFactory.Options();
   options.inJustDecodeBounds = true;
   BitmapFactory.decodeFileDescriptor(fis.getFD(), null, options);
   float srcWidth = options.outWidth;
   float srcHeight = options.outHeight;
   int inSampleSize = 1;

   if (srcHeight > height || srcWidth > width) {
    if (srcWidth > srcHeight) {
     inSampleSize = Math.round(srcHeight / height);
    } else {
     inSampleSize = Math.round(srcWidth / width);
    }
   }

   options.inJustDecodeBounds = false;
   options.inSampleSize = inSampleSize;

   return BitmapFactory.decodeFileDescriptor(fis.getFD(), null, options);
  } catch (Exception ex) {
  }
  return null;
 }

测试同样生成10张图片两种方式耗时比较 cpu使用以及内存占用两者相差无几 第二种方式效率高一点 所以建议优先采用第二种方式

  start = System.currentTimeMillis();
  for (int i = 0; i < testMaxCount; i++) {
   BitmapUtils.readBitmapFromFile(filePath, 400, 400);
  }
  end = System.currentTimeMillis();
  Log.e(TAG, "BitmapFactory decodeFile--time-->" + (end - start));

  start = System.currentTimeMillis();
  for (int i = 0; i < testMaxCount; i++) {
   BitmapUtils.readBitmapFromFileDescriptor(filePath, 400, 400);
  }
  end = System.currentTimeMillis();
  Log.e(TAG, "BitmapFactory decodeFileDescriptor--time-->" + (end - start));

3.)从输入流中读取文件

 /**
  * 获取缩放后的本地图片
  *
  * @param ins 输入流
  * @param width 宽
  * @param height 高
  * @return
  */
 public static Bitmap readBitmapFromInputStream(InputStream ins, int width, int height) {
  BitmapFactory.Options options = new BitmapFactory.Options();
  options.inJustDecodeBounds = true;
  BitmapFactory.decodeStream(ins, null, options);
  float srcWidth = options.outWidth;
  float srcHeight = options.outHeight;
  int inSampleSize = 1;

  if (srcHeight > height || srcWidth > width) {
   if (srcWidth > srcHeight) {
    inSampleSize = Math.round(srcHeight / height);
   } else {
    inSampleSize = Math.round(srcWidth / width);
   }
  }

  options.inJustDecodeBounds = false;
  options.inSampleSize = inSampleSize;

  return BitmapFactory.decodeStream(ins, null, options);
 }

4.)从资源文件中读取文件 

 public static Bitmap readBitmapFromResource(Resources resources, int resourcesId, int width, int height) {
  BitmapFactory.Options options = new BitmapFactory.Options();
  options.inJustDecodeBounds = true;
  BitmapFactory.decodeResource(resources, resourcesId, options);
  float srcWidth = options.outWidth;
  float srcHeight = options.outHeight;
  int inSampleSize = 1;

  if (srcHeight > height || srcWidth > width) {
   if (srcWidth > srcHeight) {
    inSampleSize = Math.round(srcHeight / height);
   } else {
    inSampleSize = Math.round(srcWidth / width);
   }
  }

  options.inJustDecodeBounds = false;
  options.inSampleSize = inSampleSize;

  return BitmapFactory.decodeResource(resources, resourcesId, options);
 }

此种方式相当的耗费内存 建议采用decodeStream代替decodeResource 可以如下形式

 public static Bitmap readBitmapFromResource(Resources resources, int resourcesId, int width, int height) {
  InputStream ins = resources.openRawResource(resourcesId);
  BitmapFactory.Options options = new BitmapFactory.Options();
  options.inJustDecodeBounds = true;
  BitmapFactory.decodeStream(ins, null, options);
  float srcWidth = options.outWidth;
  float srcHeight = options.outHeight;
  int inSampleSize = 1;

  if (srcHeight > height || srcWidth > width) {
   if (srcWidth > srcHeight) {
    inSampleSize = Math.round(srcHeight / height);
   } else {
    inSampleSize = Math.round(srcWidth / width);
   }
  }

  options.inJustDecodeBounds = false;
  options.inSampleSize = inSampleSize;

  return BitmapFactory.decodeStream(ins, null, options);
 }

decodeStream、decodeResource占用内存对比:

 start = System.currentTimeMillis();
  for (int i = 0; i < testMaxCount; i++) {
   BitmapUtils.readBitmapFromResource(getResources(), R.mipmap.ic_app_center_banner, 400, 400);
   Log.e(TAG, "BitmapFactory decodeResource--num-->" + i);
  }
  end = System.currentTimeMillis();
  Log.e(TAG, "BitmapFactory decodeResource--time-->" + (end - start));

  start = System.currentTimeMillis();
  for (int i = 0; i < testMaxCount; i++) {
   BitmapUtils.readBitmapFromResource1(getResources(), R.mipmap.ic_app_center_banner, 400, 400);
   Log.e(TAG, "BitmapFactory decodeStream--num-->" + i);
  }
  end = System.currentTimeMillis();
  Log.e(TAG, "BitmapFactory decodeStream--time-->" + (end - start));

BitmapFactory.decodeResource 加载的图片可能会经过缩放,该缩放目前是放在 java 层做的,效率比较低,而且需要消耗 java 层的内存。因此,如果大量使用该接口加载图片,容易导致OOM错误。
BitmapFactory.decodeStream 不会对所加载的图片进行缩放,相比之下占用内存少,效率更高。
 这两个接口各有用处,如果对性能要求较高,则应该使用 decodeStream;如果对性能要求不高,且需要 Android 自带的图片自适应缩放功能,则可以使用 decodeResource。

5. )从二进制数据读取图片

public static Bitmap readBitmapFromByteArray(byte[] data, int width, int height) {
  BitmapFactory.Options options = new BitmapFactory.Options();
  options.inJustDecodeBounds = true;
  BitmapFactory.decodeByteArray(data, 0, data.length, options);
  float srcWidth = options.outWidth;
  float srcHeight = options.outHeight;
  int inSampleSize = 1;

  if (srcHeight > height || srcWidth > width) {
   if (srcWidth > srcHeight) {
    inSampleSize = Math.round(srcHeight / height);
   } else {
    inSampleSize = Math.round(srcWidth / width);
   }
  }

  options.inJustDecodeBounds = false;
  options.inSampleSize = inSampleSize;

  return BitmapFactory.decodeByteArray(data, 0, data.length, options);
 }

6.)从assets文件读取图片

 /**
  * 获取缩放后的本地图片
  *
  * @param filePath 文件路径
  * @return
  */
 public static Bitmap readBitmapFromAssetsFile(Context context, String filePath) {
  Bitmap image = null;
  AssetManager am = context.getResources().getAssets();
  try {
   InputStream is = am.open(filePath);
   image = BitmapFactory.decodeStream(is);
   is.close();
  } catch (IOException e) {
   e.printStackTrace();
  }
  return image;
 }

图片保存文件: 

 public static void writeBitmapToFile(String filePath, Bitmap b, int quality) {
  try {
   File desFile = new File(filePath);
   FileOutputStream fos = new FileOutputStream(desFile);
   BufferedOutputStream bos = new BufferedOutputStream(fos);
   b.compress(Bitmap.CompressFormat.JPEG, quality, bos);
   bos.flush();
   bos.close();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }

图片压缩:

 private static Bitmap compressImage(Bitmap image) {
  if (image == null) {
   return null;
  }
  ByteArrayOutputStream baos = null;
  try {
   baos = new ByteArrayOutputStream();
   image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
   byte[] bytes = baos.toByteArray();
   ByteArrayInputStream isBm = new ByteArrayInputStream(bytes);
   Bitmap bitmap = BitmapFactory.decodeStream(isBm);
   return bitmap;
  } catch (OutOfMemoryError e) {
  } finally {
   try {
    if (baos != null) {
     baos.close();
    }
   } catch (IOException e) {
   }
  }
  return null;
 }

图片缩放: 

 /**
  * 根据scale生成一张图片
  *
  * @param bitmap
  * @param scale 等比缩放值
  * @return
  */
 public static Bitmap bitmapScale(Bitmap bitmap, float scale) {
  Matrix matrix = new Matrix();
  matrix.postScale(scale, scale); // 长和宽放大缩小的比例
  Bitmap resizeBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
  return resizeBmp;
 }

获取图片旋转角度:

 /**
  * 读取照片exif信息中的旋转角度
  *
  * @param path 照片路径
  * @return角度
  */
 private static int readPictureDegree(String path) {
  if (TextUtils.isEmpty(path)) {
   return 0;
  }
  int degree = 0;
  try {
   ExifInterface exifInterface = new ExifInterface(path);
   int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
   switch (orientation) {
    case ExifInterface.ORIENTATION_ROTATE_90:
     degree = 90;
     break;
    case ExifInterface.ORIENTATION_ROTATE_180:
     degree = 180;
     break;
    case ExifInterface.ORIENTATION_ROTATE_270:
     degree = 270;
     break;
   }
  } catch (Exception e) {
  }
  return degree;
 }


图片旋转角度:

  private static Bitmap rotateBitmap(Bitmap b, float rotateDegree) {
    if (b == null) {
      return null;
    }
    Matrix matrix = new Matrix();
    matrix.postRotate(rotateDegree);
    Bitmap rotaBitmap = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), matrix, true);
    return rotaBitmap;
  }

图片转二进制:

public byte[] bitmap2Bytes(Bitmap bm) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
    return baos.toByteArray();
  }

Bitmap转Drawable

public static Drawable bitmapToDrawable(Resources resources, Bitmap bm) {
    Drawable drawable = new BitmapDrawable(resources, bm);
    return drawable;
  }

Drawable转Bitmap

 public static Bitmap drawableToBitmap(Drawable drawable) {
    Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
    drawable.draw(canvas);
    return bitmap;
  }

Drawable、Bitmap占用内存探讨
 之前一直使用过Afinal 和Xutils 熟悉这两框架的都知道,两者出自同一人,Xutils是Afina的升级版,AFinal中的图片内存缓存使用的是Bitmap 而后来为何Xutils将内存缓存的对象改成了Drawable了呢?我们一探究竟 
写个测试程序:

 List<Bitmap> bitmaps = new ArrayList<>();
    start = System.currentTimeMillis();
    for (int i = 0; i < testMaxCount; i++) {
      Bitmap bitmap = BitmapUtils.readBitMap(this, R.mipmap.ic_app_center_banner);
      bitmaps.add(bitmap);
      Log.e(TAG, "BitmapFactory Bitmap--num-->" + i);
    }
    end = System.currentTimeMillis();
    Log.e(TAG, "BitmapFactory Bitmap--time-->" + (end - start));

    List<Drawable> drawables = new ArrayList<>();

    start = System.currentTimeMillis();
    for (int i = 0; i < testMaxCount; i++) {
      Drawable drawable = getResources().getDrawable(R.mipmap.ic_app_center_banner);
      drawables.add(drawable);
      Log.e(TAG, "BitmapFactory Drawable--num-->" + i);
    }
    end = System.currentTimeMillis();
    Log.e(TAG, "BitmapFactory Drawable--time-->" + (end - start));

测试数据1000 同一张图片

从测试说明Drawable 相对Bitmap有很大的内存占用优势。这也是为啥现在主流的图片缓存框架内存缓存那一层采用Drawable作为缓存对象的原因。
 小结:图片处理就暂时学习到这里,以后再做补充。

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

(0)

相关推荐

  • 直接应用项目中的Android图片缓存技术

    前不久搞的Android图片缓存,刚开始引入开源的框架,用着还行,但是在开发中遇到问题,就比如universal-image-loader-1.9.5.jar这个框架吧,在加载图片的时候自定义imageview无法加载,可能是存在以下问题吧,况且导入框架导致开发的项目包越来越大,基于上面的这几种情况,于是我就想自己写一个图片三级缓存的工具. 简要分析:刚开始想,图片的加载显示无非是先检查内存里面有没有,没就去文件里面找,若是文件里面没有的话就去开启网络下载,这样也符合开发中的大部分需求,而且效率

  • Android开发笔记之图片缓存、手势及OOM分析

    把图片缓存.手势及OOM三个主题放在一起,是因为在Android应用开发过程中,这三个问题经常是联系在一起的.首先,预览大图需要支持手势缩放,旋转,平移等操作:其次,图片在本地需要进行缓存,避免频繁访问网络:最后,图片(Bitmap)是Android中占用内存的大户,涉及高清大图等处理时,内存占用非常大,稍不谨慎,系统就会报OOM错误. 庆幸的是,这三个主题在Android开发中属于比较普遍的问题,有很多针对于此的通用的开源解决方案.因此,本文主要说明笔者在开发过程中用到的一些第三方开源库.主要

  • Android实现图片缓存与异步加载

    ImageManager2这个类具有异步从网络下载图片,从sd读取本地图片,内存缓存,硬盘缓存,图片使用动画渐现等功能,已经将其应用在包含大量图片的应用中一年多,没有出现oom. Android程序常常会内存溢出,网上也有很多解决方案,如软引用,手动调用recycle等等.但经过我们实践发现这些方案,都没能起到很好的效果,我们的应用依然会出现很多oom,尤其我们的应用包含大量的图片.android3.0之后软引用基本已经失效,因为虚拟机只要碰到软引用就回收,所以带不来任何性能的提升. 我这里的解

  • android上的一个网络接口和图片缓存框架enif简析

    1.底层网络接口采用apache的httpclient连接池框架: 2.图片缓存采用基于LRU的算法: 3.网络接口采用监听者模式: 4.包含图片的OOM处理(及时回收处理技术的应用): 图片核心处理类:CacheView.java 复制代码 代码如下: package xiaogang.enif.image; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; imp

  • Android图片缓存之初识Glide(三)

    前言: 前面总结学习了图片的使用以及Lru算法,今天来学习一下比较优秀的图片缓存开源框架.技术本身就要不断的更迭,从最初的自己使用SoftReference实现自己的图片缓存,到后来做电商项目自己的实现方案不能满足项目的需求改用Afinal,由于Afinal不再维护而选择了师出同门的Xutils,中间也接触过别的开源框架比如Picasso,对Picasso的第一次印象就不太好,初次接触是拿到了公司刚从外包公司接手过来的图片社交类app,对内存占用太大,直接感受就是导致ListView滑动有那么一

  • Android图片缓存之Lru算法(二)

    前言: 上篇我们总结了Bitmap的处理,同时对比了各种处理的效率以及对内存占用大小,点击查看.我们得知一个应用如果使用大量图片就会导致OOM(out of memory),那该如何处理才能近可能的降低oom发生的概率呢?之前我们一直在使用SoftReference软引用,SoftReference是一种现在已经不再推荐使用的方式,因为从 Android 2.3 (API Level 9)开始,垃圾回收器会更倾向于回收持有软引用或弱引用的对象,这让软引用变得不再可靠,所以今天我们来认识一种新的缓

  • Android图片缓存原理、特性对比

    这是我在 MDCC 上分享的内容(略微改动),也是源码解析第一期发布时介绍的源码解析后续会慢慢做的事. 从总体设计和原理上对几个图片缓存进行对比,没用到他们的朋友也可以了解他们在某些特性上的实现. 一. 四大图片缓存基本信息 Universal ImageLoader 是很早开源的图片缓存,在早期被很多应用使用. Picasso 是 Square 开源的项目,且他的主导者是 JakeWharton,所以广为人知. Glide 是 Google 员工的开源项目,被一些 Google App 使用,

  • android中图片的三级缓存cache策略(内存/文件/网络)

    1.简介 现在android应用中不可避免的要使用图片,有些图片是可以变化的,需要每次启动时从网络拉取,这种场景在有广告位的应用以及纯图片应用(比如百度美拍)中比较多. 现在有一个问题:假如每次启动的时候都从网络拉取图片的话,势必会消耗很多流量.在当前的状况下,对于非wifi用户来说,流量还是很贵的,一个很耗流量的应用,其用户数量级肯定要受到影响.当然,我想,向百度美拍这样的应用,必然也有其内部的图片缓存策略.总之,图片缓存是很重要而且是必须的. 2.图片缓存的原理 实现图片缓存也不难,需要有相

  • Android中Glide加载库的图片缓存配置究极指南

    零.选择Glide 为什么图片加载我首先推荐Glide? 图片加载框架用了不少,从afinal框架的afinalBitmap,Xutils的BitmapUtils,老牌框架universalImageLoader,著名开源组织square的picasso,google推荐的glide到FaceBook推出的fresco.这些我前前后后都体验过,那么面对这么多的框架,该如何选择呢?下面简单分析下我的看法. afinal和Xuils在github上作者已经停止维护了,开源社区最新的框架要属KJFra

  • android异步加载图片并缓存到本地实现方法

    在android项目中访问网络图片是非常普遍性的事情,如果我们每次请求都要访问网络来获取图片,会非常耗费流量,而且图片占用内存空间也比较大,图片过多且不释放的话很容易造成内存溢出.针对上面遇到的两个问题,首先耗费流量我们可以将图片第一次加载上面缓存到本地,以后如果本地有就直接从本地加载.图片过多造成内存溢出,这个是最不容易解决的,要想一些好的缓存策略,比如大图片使用LRU缓存策略或懒加载缓存策略.今天首先介绍一下本地缓存图片. 首先看一下异步加载缓存本地代码: 复制代码 代码如下: public

随机推荐