bitmap--Bitmap详解与Bitmap的内存优化

1、Bitmap:

Bitmap是Android系统中的图像处理的最重要类之一。用它能够获取图像文件信息,进行图像剪切、旋转、缩放等操做,并能够指定格式保存图像文件。
经常使用方法:javascript

  • 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为原图,建立新的图片,指定起始坐标以及新图像的高宽。

2、BitmapFactory工厂类:

Option 参数类:java

  • 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  //当前屏幕的像素密度

工厂方法:python

  • 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 :**
枚举变量 (位图位数越高表明其能够存储的颜色信息越多,图像越逼真,占用内存越大)android

  • 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)占用的内存=图片长度*图片宽度*单位像素占用的字节数。canvas


3、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资源加载

  1. 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。服务器

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

4、Bitmap | Drawable | InputStream | Byte[ ] 之间进行转换

  1. 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);网络

  1. Bitmap转换成Drawable
public static Drawable bitmapToDrawable(Resources resources, Bitmap bm) { Drawable drawable = new BitmapDrawable(resources, bm); return drawable; } 
  1. Bitmap转换成byte[]
public byte[] bitmap2Bytes(Bitmap bm) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.PNG, 100, baos); return baos.toByteArray(); } 
  1. byte[]转换成Bitmap
    Bitmap bitmap = BitmapFactory.decodeByteArray(byte, 0, b.length);
  2. InputStream转换成Bitmap
InputStream is = getResources().openRawResource(id); Bitmap bitmap = BitmaoFactory.decodeStream(is); 
  1. 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(); 

5、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(); } } 
  1. 图片压缩:
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; } 
  1. 图片缩放:
/** * 根据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; } 
  1. 获取图片旋转角度:
/** * 读取照片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; } 
  1. 设置图片旋转角度
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; } 
  1. 经过图片id得到Bitmap:
    Bitmap bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
  2. 经过 assest 获取 得到Drawable bitmap:
InputStream in = this.getAssets().open("ic_launcher"); Drawable da = Drawable.createFromStream(in, null); Bitmap mm = BitmapFactory.decodeStream(in); 
  1. 经过 sdcard 得到 bitmap
    Bitmap bit = BitmapFactory.decodeFile("/sdcard/android.jpg");
  2. ** 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; } 
  1. 将控件转换为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; } 
  1. ** 放大缩小图片**
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; } 
  1. 得到圆角图片的方法
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; } 
  1. **对 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; } 

6、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。

做者:闲庭CC 连接:https://www.jianshu.com/p/8206dd8b6d8b 來源:简书 简书著做权归做者全部,任何形式的转载都请联系做者得到受权并注明出处。
相关文章
相关标签/搜索