您的位置:首页 > 移动开发 > Android开发

Android解析大图

2015-11-06 09:12 537 查看

Android解析大图

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

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


解析图像主要分为两步:

1. 获取图片的宽高,这里要设置
Options.inJustDecodeBounds=true
,当这个属性为true的时候,我们就可以禁止系统加载图片到内存,但是Options参数中的图片宽高、类型等属性已经被赋值了,这样,我们就实现了不使用内存就获取图片的属性。

2. 设置合适的压缩比例inSampleSize,这个属性可以设置图片的缩放比例,例如一张1000 X 1000像素的图片,设置inSampleSize为5,意思就是把这个图片缩放到了五分之一,即200 X 200 。

简单流程图:

Created with Raphaël 2.1.0StartBitmap path,width,heightdecodeFile(inJustDecodeBounds=true)calculate inSampleSizedecodeFile(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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: