Android解析大图

Android解析大图

标签(空格分隔): Android开发


通常,解析图像会用到BitmapFactory类中的decodeFile方法来获得一个Bitmap对象。但当图像很大时,就会出现OOM(Out of Memory)。这时就需要用到BitmapFactory.Options,需要设置的有BitmapFactory.inJustDecodeBoundsBitmapFactory.inSampleSize

解析图像主要分为两步:
1. 获取图片的宽高,这里要设置Options.inJustDecodeBounds=true,当这个属性为true的时候,我们就可以禁止系统加载图片到内存,但是Options参数中的图片宽高、类型等属性已经被赋值了,这样,我们就实现了不使用内存就获取图片的属性。
2. 设置合适的压缩比例inSampleSize,这个属性可以设置图片的缩放比例,例如一张1000 X 1000像素的图片,设置inSampleSize为5,意思就是把这个图片缩放到了五分之一,即200 X 200 。

简单流程图:

Created with Raphaël 2.1.0 Start Bitmap path,width,height decodeFile(inJustDecodeBounds=true) calculate inSampleSize decodeFile(inJustDecodeBounds=false) End

代码:

public Bitmap decodeSampledBitmapFromSD(String path, int reqWidth, int reqHeight) {

     Bitmap bm = null;
     // First decode with inJustDecodeBounds=true to check dimensions
     final BitmapFactory.Options options = new BitmapFactory.Options();
     options.inJustDecodeBounds = true;
     BitmapFactory.decodeFile(path, options);

     // Calculate inSampleSize
     options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

     // Decode bitmap with inSampleSize set
     options.inJustDecodeBounds = false;
     bm = BitmapFactory.decodeFile(path, options);

     return bm;
    }

// 计算SampleSize的方法有很多,这是其中一种比较简单的
public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
     final int height = options.outHeight;
     final int width = options.outWidth;
     int inSampleSize = 1;

     if (height > reqHeight || width > reqWidth) {
         if (width > height) {
             inSampleSize = Math.round((float) height
                     / (float) reqHeight);
         } else {
             inSampleSize = Math.round((float) width / (float) reqWidth);
         }
     }

     return inSampleSize;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值