Android解析大图
2015-11-06 09:12
537 查看
Android解析大图
标签(空格分隔): Android开发通常,解析图像会用到BitmapFactory类中的decodeFile方法来获得一个Bitmap对象。但当图像很大时,就会出现OOM(Out of Memory)。这时就需要用到
BitmapFactory.Options,需要设置的有
BitmapFactory.inJustDecodeBounds和
BitmapFactory.inSampleSize。
解析图像主要分为两步:
1. 获取图片的宽高,这里要设置
Options.inJustDecodeBounds=true,当这个属性为true的时候,我们就可以禁止系统加载图片到内存,但是Options参数中的图片宽高、类型等属性已经被赋值了,这样,我们就实现了不使用内存就获取图片的属性。
2. 设置合适的压缩比例inSampleSize,这个属性可以设置图片的缩放比例,例如一张1000 X 1000像素的图片,设置inSampleSize为5,意思就是把这个图片缩放到了五分之一,即200 X 200 。
简单流程图:
Created with Raphaël 2.1.0StartBitmap path,width,heightdecodeFile(inJustDecodeBounds=true)calculate inSampleSizedecodeFile(inJustDecodeBounds=false)End
代码:
public Bitmap decodeSampledBitmapFromSD(String path, int reqWidth, int reqHeight) { Bitmap bm = null; // First decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(path, options); // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; bm = BitmapFactory.decodeFile(path, options); return bm; } // 计算SampleSize的方法有很多,这是其中一种比较简单的 public int calculateInSampleSize(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) { if (width > height) { inSampleSize = Math.round((float) height / (float) reqHeight); } else { inSampleSize = Math.round((float) width / (float) reqWidth); } } return inSampleSize; }
相关文章推荐
- Android Activity间数据传输
- Android音乐播放器(2)从SD卡中读取音乐
- android82 文件下载框架xUtils
- android模拟器,Genymotion问题:Unable to start the virtual device.
- android状态机statemachine详解
- Android的屏幕适配之图片加载适配
- Android中Bitmap, Drawable, Byte,ID之间的转化
- android String.xml文件键值无法修改
- Layout_weight注意事项
- 绝大部分 Android 手电筒应用需要大量权限
- Android自定义Chronometer实现短信验证码秒表倒计时功能
- Android 来电归属地显示功能demo
- Android中利用广播接受者简单几步实现拨号显示归属地
- Android 下自定义Toast
- Android内容提供器简单实例(读取系统联系人)
- Android的AsyncTask类的简单教程
- Android之NDK开发
- android源码中的资源文件目录
- 20-2第一篇:关于android对话框
- Android Studio 插件