Android 中的缩略图的加载

来源:互联网 发布:冷冰网络歌手 编辑:程序博客网 时间:2024/04/29 23:05

//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);            }        }
0 0
原创粉丝点击