android imageview 加载大图片防止内存溢出的方法

原创
2014/06/10 12:39
阅读数 4.3K
// width height 实际需要的图片尺寸,为了保证裁剪的图片不变形,最好还是算一下缩放比例,这里就不写了
public static Bitmap loadBitmap(String url, int width, int height)
{
    Bitmap bitmap = null;
    if (url == null || !new File(url).exists()) return bitmap;
    try
    {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(url, opts);
        opts.inSampleSize = calculateSampleSize(opts, width, height);
        opts.inJustDecodeBounds = false;
        opts.inPreferredConfig = Bitmap.Config.RGB_565;
        opts.inPurgeable = true;
        opts.inInputShareable = true;
        bitmap = BitmapFactory.decodeStream(new FileInputStream(url), null, opts);
        bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height);
        return bitmap;
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    return bitmap;
}

private static int calculateSampleSize(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;
}

sample size就是压缩比例,本质上就是设置恰当的sample size将大的图片尺寸转成相等或略大于我们需要的实际图片尺寸。

inSampleSize*2 是因为官方文档里面提到2的乘方效率最高。


展开阅读全文
加载中
点击加入讨论🔥(1) 发布并加入讨论🔥
1 评论
5 收藏
0
分享
返回顶部
顶部