【Android】图片显示内存优化(解决“bitmap size exceeds VM budget”异常)
16lz
2021-01-23
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。
更多相关文章
- android保存全局变量
- 1.1使用内置的Camara应用程序捕捉图像
- Ubuntu 设置Android adb 环境变量
- Java环境变量和Android环境变量
- android中Bitmap图像处理 修改图片大小以及保存时的文件大小
- java android maven环境变量基本配置