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

Android Bitmap详解及Bitmap的内存优化

程序员文章站 2023-11-28 16:50:04
android bitmap详解及bitmap的内存优化 一、bitmap: bitmap是android系统中的图像处理的最重要类之一。用它可以获取图像文件信息,进行...

android bitmap详解及bitmap的内存优化

一、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等无损格式的图片,会忽略此项设置。
    stream: outputstream中写入压缩数据。
    return: 是否成功压缩到指定的流。
  • 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,不获取图片,不分配内存,但会返回图片的高度宽度信息。如果将这个值置为true,那么在解码的时候将不会返回bitmap,只会返回这个bitmap的尺寸。这个属性的目的是,如果你只想知道一个bitmap的尺寸,但又不想将其加载到内存时。这是一个非常有用的属性。
  • public int insamplesize //图片缩放的倍数,  这个值是一个int,当它小于1的时候,将会被当做1处理,如果大于1,那么就会按照比例(1 / insamplesize)缩小bitmap的宽和高、降低分辨率,大于1时这个值将会被处置为2的倍数。例如,width=100,height=100,insamplesize=2,那么就会将bitmap处理为,width=50,height=50,宽高降为1 / 2,像素数降为1 / 4。
  • public int outwidth //获取图片的宽度值
  • public int outheight //获取图片的高度值 ,表示这个bitmap的宽和高,一般和injustdecodebounds一起使用来获得bitmap的宽高,但是不加载到内存。
  • public int indensity //用于位图的像素压缩比
  • public int intargetdensity //用于目标位图的像素压缩比(要生成的位图)
  • public byte[] intempstorage  //创建临时文件,将图片存储
  • public boolean inscaled //设置为true时进行图片压缩,从indensity到intargetdensity
  • public boolean indither  //如果为true,解码器尝试抖动解码
  • public bitmap.config inpreferredconfig  //设置解码器,这个值是设置色彩模式,默认值是argb_8888,在这个模式下,一个像素点占用4bytes空间,一般对透明度不做要求的话,一般采用rgb_565模式,这个模式下一个像素点占用2bytes。
  • 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 :

枚举变量 (位图位数越高代表其可以存储的颜色信息越多,图像越逼真,占用内存越大)

  1. public static final bitmap.config alpha_8  //代表8位alpha位图 每个像素占用1byte内存
  2. public static final bitmap.config argb_4444  //代表16位argb位图 每个像素占用2byte内存
  3. public static final bitmap.config argb_8888  //代表32位argb位图 每个像素占用4byte内存
  4. public static final bitmap.config rgb_565  //代表8位rgb位图 每个像素占用2byte内存

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

三、bitmap加载方式

bitmap的加载方式有resource资源加载、本地(sdcard)加载、网络加载等加载方式。

1. 从本地(sdcard)文件读取

方式一

/**
 * 获取缩放后的本地图片
 *
 * @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);
 }

方式二 (效率高于方式一)

/**
 * 获取缩放后的本地图片
 *
 * @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;
 }

2. 从输入流中读取文件(网络加载)

/**
   * 获取缩放后的本地图片
   *
   * @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);
  }

3.resource资源加载

res资源加载方式:

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

bitmapfactory.decoderesource 加载的图片可能会经过缩放,该缩放目前是放在 java 层做的,效率比较低,而且需要消耗 java 层的内存。因此,如果大量使用该接口加载图片,容易导致oom错误

bitmapfactory.decodestream 不会对所加载的图片进行缩放,相比之下占用内存少,效率更高。

这两个接口各有用处,如果对性能要求较高,则应该使用 decodestream;如果对性能要求不高,且需要 android 自带的图片自适应缩放功能,则可以使用 decoderesource。

2.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;
}

4.从二进制数据读取图片

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

四、bitmap | drawable | inputstream | byte[ ] 之间进行转换

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的获取方式:drawable drawable = getresources().getdrawable(r.drawable.ic_launcher);

2.bitmap转换成drawable

public static drawable bitmaptodrawable(resources resources, bitmap bm) {
  drawable drawable = new bitmapdrawable(resources, bm);
  return drawable;
}

3.bitmap转换成byte[]

public byte[] bitmap2bytes(bitmap bm) {
  bytearrayoutputstream baos = new bytearrayoutputstream();
  bm.compress(bitmap.compressformat.png, 100, baos);
  return baos.tobytearray();
}

4.byte[]转换成bitmap

bitmap bitmap = bitmapfactory.decodebytearray(byte, 0, b.length);

5.inputstream转换成bitmap

inputstream is = getresources().openrawresource(id); 
bitmap bitmap = bitmaofactory.decodestream(is);

6.inputstream转换成byte[]

inputstream is = getresources().openrawresource(id);//也可以通过其他方式接收一个inputstream对象 
bytearrayoutputstream baos = new bytearrayoutputstream();  
byte[] b = new byte[1024*2];  
int len = 0;  
while ((len = is.read(b, 0, b.length)) != -1)  
{  
baos.write(b, 0, len);  
baos.flush();  
}  
byte[] bytes = baos.tobytearray();

五、bitmap简单操作

1.将bitmap保存为本地文件:

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

2.图片压缩:

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

3.图片缩放:

/**
 * 根据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;
}

4.获取图片旋转角度:

/**
 * 读取照片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;
}

5.设置图片旋转角度

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

6.通过图片id获得bitmap:

bitmap bitmap=bitmapfactory.decoderesource(getresources(), r.drawable.ic_launcher);

7.通过 assest 获取 获得drawable bitmap:

inputstream in = this.getassets().open("ic_launcher");
drawable da = drawable.createfromstream(in, null);
bitmap mm = bitmapfactory.decodestream(in);

8.通过 sdcard 获得 bitmap

bitmap bit = bitmapfactory.decodefile("/sdcard/android.jpg");

9.view转bitmap

public static bitmap convertviewtobitmap(view view, int bitmapwidth, int bitmapheight){
bitmap bitmap = bitmap.createbitmap(bitmapwidth, bitmapheight, bitmap.config.argb_8888);
view.draw(new canvas(bitmap));
return bitmap;
}

10.将控件转换为bitmap

public static bitmap convertviewtobitmap(view view){
// 打开图像缓存
view.setdrawingcacheenabled(true);
// 必须调用measure和layout方法才能成功保存可视组件的截图到png图像文件
// 测量view大小
view.measure(measurespec.makemeasurespec(0, measurespec.unspecified), measurespec.makemeasurespec(0, measurespec.unspecified));
// 发送位置和尺寸到view及其所有的子view
view.layout(0, 0, view.getmeasuredwidth(), view.getmeasuredheight());
// 获得可视组件的截图
bitmap bitmap = view.getdrawingcache();
return bitmap;
}
public static bitmap getbitmapfromview(view view){
bitmap returnedbitmap = bitmap.createbitmap(view.getwidth(), view.getheight(), bitmap.config.argb_8888);
canvas canvas = new canvas(returnedbitmap);
drawable bgdrawable = view.getbackground();
if (bgdrawable != null)
  bgdrawable.draw(canvas);
else
  canvas.drawcolor(color.white);
view.draw(canvas);
return returnedbitmap;
}

11.放大缩小图片

public static bitmap zoombitmap(bitmap bitmap,int w,int h){ 
int width = bitmap.getwidth(); 
int height = bitmap.getheight(); 
matrix matrix = new matrix(); 
float scalewidht = ((float)w / width); 
float scaleheight = ((float)h / height); 
matrix.postscale(scalewidht, scaleheight); 
bitmap newbmp = bitmap.createbitmap(bitmap, 0, 0, width, height, matrix, true); 
return newbmp; 
}

12.获得圆角图片的方法

public static bitmap getroundedcornerbitmap(bitmap bitmap,float roundpx){ 

bitmap output = bitmap.createbitmap(bitmap.getwidth(), bitmap 
    .getheight(), config.argb_8888); 
canvas canvas = new canvas(output); 

final int color = 0xff424242; 
final paint paint = new paint(); 
final rect rect = new rect(0, 0, bitmap.getwidth(), bitmap.getheight()); 
final rectf rectf = new rectf(rect); 

paint.setantialias(true); 
canvas.drawargb(0, 0, 0, 0); 
paint.setcolor(color); 
canvas.drawroundrect(rectf, roundpx, roundpx, paint); 

paint.setxfermode(new porterduffxfermode(mode.src_in)); 
canvas.drawbitmap(bitmap, rect, rect, paint); 

return output; 
}

13.对 bitmap 进行裁剪

public bitmap bitmapclip(context context , int id , int x , int y){
bitmap map = bitmapfactory.decoderesource(context.getresources(), id);
map = bitmap.createbitmap(map, x, y, 120, 120);
return map;
}

六、bitmap的内存优化详解

在android应用里,最耗费内存的就是图片资源。而且在android系统中,读取位图bitmap时,分给虚拟机中的图片的堆栈大小只有8m,如果超出了,就会出现outofmemory异常。所以,对于图片的内存优化,是android应用开发中比较重要的内容。

1. 要及时回收bitmap的内存

bitmap类有一个方法recycle(),从方法名可以看出意思是回收。这里就有疑问了,android系统有自己的垃圾回收机制,可以不定期的回收掉不使用的内存空间,当然也包括bitmap的空间。那为什么还需要这个方法呢?

bitmap类的构造方法都是私有的,所以开发者不能直接new出一个bitmap对象,只能通过bitmapfactory类的各种静态方法来实例化一个bitmap。仔细查看bitmapfactory的源代码可以看到,生成bitmap对象最终都是通过jni调用方式实现的。所以,加载bitmap到内存里以后,是包含两部分内存区域的。简单的说,一部分是java部分的,一部分是c部分的。这个bitmap对象是由java部分分配的,不用的时候系统就会自动回收了,但是那个对应的c可用的内存区域,虚拟机是不能直接回收的,这个只能调用底层的功能释放。所以需要调用recycle()方法来释放c部分的内存。从bitmap类的源代码也可以看到,recycle()方法里也的确是调用了jni方法了的。

那如果不调用recycle(),是否就一定存在内存泄露呢?也不是的。android的每个应用都运行在独立的进程里,有着独立的内存,如果整个进程被应用本身或者系统杀死了,内存也就都被释放掉了,当然也包括c部分的内存。
android对于进程的管理是非常复杂的。简单的说,android系统的进程分为几个级别,系统会在内存不足的情况下杀死一些低优先级的进程,以提供给其它进程充足的内存空间。在实际项目开发过程中,有的开发者会在退出程序的时候使用process.killprocess(process.mypid())的方式将自己的进程杀死,但是有的应用仅仅会使用调用activity.finish()方法的方式关闭掉所有的activity。

释放bitmap的示例代码片段:

// 先判断是否已经回收
if(bitmap != null && !bitmap.isrecycled()){ 
    // 回收并且置为null
    bitmap.recycle(); 
    bitmap = null; 
} 
system.gc();

从上面的代码可以看到,bitmap.recycle()方法用于回收该bitmap所占用的内存,接着将bitmap置空,最后使用system.gc()调用一下系统的垃圾回收器进行回收,可以通知垃圾回收器尽快进行回收。这里需要注意的是,调用system.gc()并不能保证立即开始进行回收过程,而只是为了加快回收的到来。

如何调用recycle()方法进行回收已经了解了,那什么时候释放bitmap的内存比较合适呢?一般来说,如果代码已经不再需要使用bitmap对象了,就可以释放了。释放内存以后,就不能再使用该bitmap对象了,如果再次使用,就会抛出异常。所以一定要保证不再使用的时候释放。比如,如果是在某个activity中使用bitmap,就可以在activity的onstop()或者ondestroy()方法中进行回收。

2.捕获异常

为了避免应用在分配bitmap内存的时候出现outofmemory异常以后crash掉,需要特别注意实例化bitmap部分的代码。通常,在实例化bitmap的代码中,一定要对outofmemory异常进行捕获。

bitmap bitmap = null;
try {
  // 实例化bitmap
  bitmap = bitmapfactory.decodefile(path);
} catch (outofmemoryerror e) {
  //
}
if (bitmap == null) {
  // 如果实例化失败 返回默认的bitmap对象
  return defaultbitmapmap;
}

这里对初始化bitmap对象过程中可能发生的outofmemory异常进行了捕获。如果发生了outofmemory异常,应用不会崩溃,而是得到了一个默认的bitmap图。

注意:很多开发者会习惯性的在代码中直接捕获exception。但是对于outofmemoryerror来说,这样做是捕获不到的。因为outofmemoryerror是一种error,而不是exception。在此仅仅做一下提醒,避免写错代码而捕获不到outofmemoryerror。

3.缓存通用的bitmap对象

有时候,可能需要在一个activity里多次用到同一张图片。比如一个activity会展示一些用户的头像列表,而如果用户没有设置头像的话,则会显示一个默认头像,而这个头像是位于应用程序本身的资源文件中的。
如果有类似上面的场景,就可以对同一bitmap进行缓存。如果不进行缓存,尽管看到的是同一张图片文件,但是使用bitmapfactory类的方法来实例化出来的bitmap,是不同的bitmap对象。缓存可以避免新建多个bitmap对象,避免内存的浪费。
在android应用开发过程中,也会经常使用缓存的技术。这里所说的缓存有两个级别,一个是硬盘缓存,一个是内存缓存。比如说,在开发网络应用过程中,可以将一些从网络上获取的数据保存到sd卡中,下次直接从sd卡读取,而不从网络中读取,从而节省网络流量。这种方式就是硬盘缓存。再比如,应用程序经常会使用同一对象,也可以放到内存中缓存起来,需要的时候直接从内存中读取。这种方式就是内存缓存。

4.压缩图片

如果图片像素过大,使用bitmapfactory类的方法实例化bitmap的过程中,需要大于8m的内存空间,就必定会发生outofmemory异常。这个时候该如何处理呢?如果有这种情况,则可以将图片缩小,以减少载入图片过程中的内存的使用,避免异常发生。

使用bitmapfactory.options设置insamplesize就可以缩小图片。属性值insamplesize表示缩略图大小为原始图片大小的几分之一。即如果这个值为2,则取出的缩略图的宽和高都是原始图片的1/2,图片的大小就为原始大小的1/4。

如果知道图片的像素过大,就可以对其进行缩小。那么如何才知道图片过大呢?

使用bitmapfactory.options设置injustdecodebounds为true后,再使用decodefile()等方法,并不会真正的分配空间,即解码出来的bitmap为null,但是可计算出原始图片的宽度和高度,即options.outwidth和options.outheight。通过这两个值,就可以知道图片是否过大了。

bitmapfactory.options opts = new bitmapfactory.options();
  // 设置injustdecodebounds为true
  opts.injustdecodebounds = true;
  // 使用decodefile方法得到图片的宽和高
  bitmapfactory.decodefile(path, opts);
  // 打印出图片的宽和高
  log.d("example", opts.outwidth + "," + opts.outheight);

在实际项目中,可以利用上面的代码,先获取图片真实的宽度和高度,然后判断是否需要跑缩小。如果不需要缩小,设置insamplesize的值为1。如果需要缩小,则动态计算并设置insamplesize的值,对图片进行缩小。需要注意的是,在下次使用bitmapfactory的decodefile()等方法实例化bitmap对象前,别忘记将opts.injustdecodebound设置回false。否则获取的bitmap对象还是null。

注意:如果程序的图片的来源都是程序包中的资源,或者是自己服务器上的图片,图片的大小是开发者可以调整的,那么一般来说,就只需要注意使用的图片不要过大,并且注意代码的质量,及时回收bitmap对象,就能避免outofmemory异常的发生。
如果程序的图片来自外界,这个时候就特别需要注意outofmemory的发生。一个是如果载入的图片比较大,就需要先缩小;另一个是一定要捕获异常,避免程序crash。

 感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!