利用BitmapFactory.Options类解决图片过大问题

来源:互联网 发布:淘宝卖家被敲诈 编辑:程序博客网 时间:2024/05/18 02:36

要展示图片给用户看时,其实只需要实现大小合适的Bitmap对象就可以了,如果要从文件生成BItmap对象,需要BitmapFactory类:

Bitmap bitmap=BitmapFactory.decodeFile(mPhotoFile.getPath());

然而,Bitmap是一个简单对象,只能存储实际像素值。因此,哪怕图片已经压缩过了,一存入Bitmap中,文件还是会放大,比如就一张5M的jpg,存入Bitmap立马变成40多M。
所以,我们需要手工对图片进行缩放。先放下实现代码类:

public class PictureUtils {    public static Bitmap getScaledBitmap(String path,int destWidth,int destHeight){        BitmapFactory.Options options=new BitmapFactory.Options();        options.inJustDecodeBounds=true;        BitmapFactory.decodeFile(path,options);        float srcWidth=options.outWidth;        float srcHeight=options.outHeight;        int inSampleSize=1;        if(srcHeight>destHeight||srcWidth>destWidth){            if(srcWidth>srcHeight){                inSampleSize=Math.round(srcHeight/destHeight);            }else{                inSampleSize=Math.round(srcWidth/destWidth);            }        }        options=new BitmapFactory().Options();        options.inSampleSize=inSampleSize;        return BitmapFactory.decodeFile(path,options);    }}

BitmapFactory.Options这个类,有一个字段inJustDecodeBounds,
如果我们把这个字段设为true,那么BitmapFactory.decodeFile(String , Options )并不会真的返回一个Bitmap给你,它仅仅会把它的宽,高返回。

然后再说一下inSampleSize,这个值是核心,可以决定缩略像素的大小。值为1时,表示缩略图和原始照片一样大小。如果是2,水平像素就是2:1,缩略图像素就是原始照片的1/4. 通过这些处理,最后把合适大小的图片返回。

0 0