Android 按指定大小读取图片的实例
程序员文章站
2024-03-05 17:40:37
在android开发中,我们经常遇到android读取图片大小超过屏幕显示的图(一般只要显示一定规格的预览图即可),在图片特别多或者图片显示很频繁的时候要特别注意这个问题,...
在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 读取图片大小显示的问题,有需要的朋友可以参考下。