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。

更多相关文章

  1. android保存全局变量
  2. 1.1使用内置的Camara应用程序捕捉图像
  3. Ubuntu 设置Android adb 环境变量
  4. Java环境变量和Android环境变量
  5. android中Bitmap图像处理 修改图片大小以及保存时的文件大小
  6. java android maven环境变量基本配置

随机推荐

  1. Android(安卓)获取音频焦点工具类
  2. pytorch模型转ncnn,并移植android
  3. android ScrollView和ListView固定底部
  4. Web integration
  5. Java HttpClient 的简单应用
  6. VLC for Android(安卓)on Linux
  7. Android实现点击切换视图并跳转传值
  8. Where To Start - Learning Android(安卓
  9. 使用webview打开浏览器
  10. 弹出式菜单PopMenu