`
dyingbleed
  • 浏览: 116514 次
  • 性别: Icon_minigender_1
  • 来自: 东莞
社区版块
存档分类
最新评论

【Android】图片显示内存优化(解决“bitmap size exceeds VM budget”异常)

 
阅读更多

 

	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。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics