有时候运用BitmapFactory.decodeFile(Sting file) 将图片转换成Bitmap方法 时会出现OOM(内存溢出)的错误,显然是因为图片太大了,那我们怎么解决呢,那就要用到 BitmapFactory.Options 了。
BitmapFactory.Options 里有一个inJustDecodeBounds,将它设置为true,再用 bitmap = BitmapFactory.decodeFile(Fileuri,options);它就只会将原图片的宽带和高度返回给你,既options.outWidth和options.outHeight。
这里要注意一下,options.inJustDecodeBounds=true;与options.inJustDecodeBounds = false;要成对出现,后面得到宽高后将它变回来。
经过上述操作后怎么设置我们所需要的图的大小呢?
那就先要得到缩放后的宽高了,比如我们需要宽高都为200的缩略图。
为了保持图片不变形,我们可以还可以进行一些运算。
int beWidth = options.outWidth/200;
int beHeight = options.outHeight/200;
int be=1;
if (beWidth<beHeight){
be=beHeight;
}else{
be=beHeight;
}
if (be<=0){
be=1;
}
为了节省内存我们需要用到BitmapFactory.Options这个类里的 inSampleSize 这个成员变量。
这个变量值可以通过可以根据图片实际的宽高和我们期望的宽高来计算得到这个值。也就是上面代码中的变量be
最后再运用一下代码:
bitmap = BitmapFactory.decodeFile(uri,options);
bitmap=ThumbnailUtils.extractThumbnail(bitmap,200,200,ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
这样就得到了我们想要的大小为200的缩略图。
最后贴上完整代码:
public Bitmap getImageThumbnail(String uri,int width,int height){
Bitmap bitmap = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds=true;
bitmap = BitmapFactory.decodeFile(uri,options);
options.inJustDecodeBounds = false;
int beWidth = options.outWidth/width;
int beHeight = options.outHeight/height;
int be=1;
if (beWidth < beHeight){
be=beHeight;
}else{
be=beHeight;
}
if (be<=0){
be=1;
}
options.inSampleSize = be;
bitmap = BitmapFactory.decodeFile(uri,options);
bitmap = ThumbnailUtils.extractThumbnail(bitmap,width,height,ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
return bitmap;
}