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

Android 中的缩略图的加载

2016-02-16 19:40 696 查看
//Android 中的缩略图加载

/*
1、使用inJustDecodeBounds,读Bitmap的长和宽
2、根据bitmap的长宽和目标缩略图的长和宽。计算出inSampleSize的大小
3、使用inSampleSize,载入一个大一点的缩略图A
4、使用createScaseBitmap,将缩略图A,生成我们需要的缩略图B
5、回收缩略图A
*/

/*
Notice
createScaseBitmap如果原图和目标缩略图大小一致,那么不会生成一个新的Bitmap直接返回bitmap,因此,回收的时候,要判断缩略图A是否就是缩略图B,如果说是的话,不要回收
*/

//代码:


public class BitmapUtils{
//计算inSampleSize的大小
private static 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){
final int halfHeight = height/2;
final int halfWidth = width/2;
while((halfHeight/inSampleSize)>reqHeight&&(halfWidth/inSampleSize)>reqWidth){
inSampleSize*=2;
}
}
return inSampleSize;
}

//创建新的Bitmap 图片对象
private static Bitmap createScaleBitmap(Bitmap src,int dstWidth.int dstHeight){
Bitmap dst=Bitmap.createScaleBitmap(src,dstWidth,dstHeight,false);
if(src!=dst){ //如果没有缩放,那么不回收
src.recycle(); //释放Bitmap的native像素数组
}
return dst;
}

//从Resources中加载图片
public static Bitmap decodeSampleBitmapFromResource(Resource res,int resId,int reqWidth,int reqHeight){
final BitmapFactory.Options options= new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res,resId,options);  //读取图片长宽
options.inSampleSize = calculateInSampleSize(options,reqWidth,reqHeight);//计算inSampleSize
options.inJustDecodeBounds = false;
Bitmap src = BitmapFactory.decodeResource(res,resId,options); //载入一个稍大的缩略图
return createScaleBitmap(src,reqWidht,reqHeight);  //进一步得到目标大小的缩略图
}

//从sd卡上加载图片
public static Bitmap decodeSampleBitmapFromFd(String pathName,int reqWidth,int reqHeight){
final BitmapFactory.Options options= new BitmapFactory.Options();
options.inJustDecodeBounds =  true;
BitmapFactory.decodeFile(pathName,options);  //获取图片的长宽
options.inSampleSize = calculateSampleSize(options,reqWidth,reqHeight);
options.inJustDecodeBounds= false;
Bitmap src =  BitmapFactory.decodeFile(pathName,options);
return createScaleBitmap(src,reqWidth,reqHeight);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: