Android 按指定大小读取图片的实例
2016-07-13 15:47
567 查看
在Android开发中,我们经常遇到Android读取图片大小超过屏幕显示的图(一般只要显示一定规格的预览图即可),在图片特别多或者图片显示很频繁的时候要特别注意这个问题,下面介绍个按指定大小读取图像的方法。
实现原理:首先获取图片文件的图像高和宽,如果小于指定比例,则直接读取;如果超过比例则按指定比例压缩读取。
捕获OutOfMemoryError时注意点:后面返回的是null,不要马上从别的地方再读图片,包括R文件中的,不然依然会抛出这个异常,一般在初始化的时候缓存默认图片,然后显示缓存中的图片。
/** 获取图像的宽高**/
public static int[] getImageWH(String path) { int[] wh = {-1, -1}; if (path == null) { return wh; } File file = new File(path); if (file.exists() && !file.isDirectory()) { try { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; InputStream is = new FileInputStream(path); BitmapFactory.decodeStream(is, null, options); wh[0] = options.outWidth; wh[1] = options.outHeight; } catch (Exception e) { Log.w(TAG, "getImageWH Exception.", e); } } return wh; } public static Bitmap createBitmapByScale(String path, int scale) { Bitmap bm = null; try { //获取宽高 int[] wh = getImageWH(path); if (wh[0] == -1 || wh[1] == -1) { return null; } //读取图片 BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = Math.max(wh[0]/scale, wh[1]/scale); InputStream is = new FileInputStream(path); bm = BitmapFactory.decodeStream(is, null, options); } catch (Exception e) { Log.w(TAG, "createBitmapByScale Exception.", e); } catch (OutOfMemoryError e) { Log.w(TAG, "createBitmapByScale OutOfMemoryError.", e); //TODO: out of memory deal.. } return bm; }
以上就是解决Android 读取图片大小显示的问题,有需要的朋友可以参考下。
您可能感兴趣的文章:
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android IPC进程间通讯机制
- Android Manifest 用法
- [转载]Activity中ConfigChanges属性的用法
- Android之获取手机上的图片和视频缩略图thumbnails
- Android之使用Http协议实现文件上传功能
- Android学习笔记(二九):嵌入浏览器
- android string.xml文件中的整型和string型代替
- i-jetty环境搭配与编译
- android之定时器AlarmManager
- android wifi 无线调试
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- android 代码实现控件之间的间距
- android FragmentPagerAdapter的“标准”配置
- Android"解决"onTouch和onClick的冲突问题
- android:installLocation简析
- android searchView的关闭事件
- SourceProvider.getJniDirectories