欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2024-03-05 14:04:48
前言: 最近准备研究一下图片缓存框架,基于这个想法觉得还是先了解有关图片缓存的基础知识,今天重点学习一下bitmap、bitmapfactory这两个类。 ...

前言:
最近准备研究一下图片缓存框架,基于这个想法觉得还是先了解有关图片缓存的基础知识,今天重点学习一下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 同一张图片

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

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

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