---
title: "【Android】图片显示内存优化（解决“bitmap size exceeds VM budget”异常）"
author: "dyingbleed"
date: "2011-09-19T12:03:28Z"
tags: []
categories: ["移动开发"]
slug: "android-bitmap-size-exceeds-vm-budget"
draft: false
lastmod: "2011-09-27T11:10:56Z"
id: 1175007
url: "https://dyingbleed.iteye.com/blog/1175007"
---

```
	public Bitmap optimizeBitmap(byte[] resource, int maxWidth, int maxHeight) {
		Bitmap result = null;
		int length = resource.length;
		BitmapFactory.Options options = new BitmapFactory.Options();	
		options.inJustDecodeBounds = true;
		result = BitmapFactory.decodeByteArray(resource, 0, length, options);
		int widthRatio = (int) Math.ceil(options.outWidth / maxWidth);
		int heightRatio = (int) Math.ceil(options.outHeight / maxHeight);
		if(widthRatio > 1 || heightRatio > 1) {
			if(widthRatio > heightRatio) {
				options.inSampleSize = widthRatio;
			} else {
				options.inSampleSize = heightRatio;
			}
		}
		options.inJustDecodeBounds = false;
		result = BitmapFactory.decodeByteArray(resource, 0, length, options);
		return result;
	}
	
```

 

 

Android Emulator的内存只有8M，当需要显示较多大图时，极易抛出“bitmap size exceeds VM budget ”的异常。

BitmapFactory.Options的公有boolean型成员变量inJustDecodeBounds，当值设置为true时，解码器返回NULL，我们可以在图像未加载内存的情况下查询图像。

示例代码中，我们通过Options对象实例options获得了图像的宽度和高度。

BitmapFactory.Options的公有int型成员变量inSampleSize用于设置图像的缩小比例，例如当inSampleSize设置为4时，编码器将返回原始1/4大小的图像。

 

注意：需要编码器返回图像时，记得将inJustDecodeBounds的值设为false。