Android从SD卡和Res读取图片,防止发生OOM内存移除
16lz
2021-12-04
/** * 从SD卡读Bitmap * @author YOLANDA * @param filePath * @param reqWidth * @param reqHeight * @return */public static Bitmap getBitmapFromSdCard(String filePath, int reqWidth, int reqHeight) {final BitmapFactory.Options options = new BitmapFactory.Options();options.inJustDecodeBounds = true;BitmapFactory.decodeFile(filePath, options);options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);options.inJustDecodeBounds = false;return BitmapFactory.decodeFile(filePath, options);}/** * 计算样本大小 * @author YOLANDA * @param options * @param reqWidth * @param reqHeight * @return */private static 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) {final int heightRatio = Math.round((float) height / (float) reqHeight);final int widthRatio = Math.round((float) width / (float) reqWidth);inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;}return inSampleSize;}/** * 从资源中按照ID读取图片(防止OOM) * @author YOLANDA * @param res * @param id * @param height * @return */public static Bitmap getBitmapFromRes(Resources res, int resId, int height) {Bitmap b = null;try {Options options = new Options();options.inJustDecodeBounds = true;BitmapFactory.decodeResource(res, resId, options);if (options.outHeight == 0) {return null;}options.inJustDecodeBounds = false;int hScale = options.outHeight / height;options.inSampleSize = hScale;options.inJustDecodeBounds = false;InputStream is = res.openRawResource(resId);b = BitmapFactory.decodeStream(is, null, options);} catch (OutOfMemoryError e) {System.gc();//回收内存}return b;}/** * 从内存卡读取图片(防止OOM) * @author YOLANDA * @param fileName * @param height * @return */public static Bitmap getBitmpFromSDCard(String fileName, int height) {Bitmap b = null;BitmapFactory.Options o2 = null;try {BitmapFactory.Options o = new BitmapFactory.Options();o.inJustDecodeBounds = true;FileInputStream fis;fis = new FileInputStream(fileName);BitmapFactory.decodeStream(fis, null, o);fis.close();int scale = o.outHeight / height;o2 = new BitmapFactory.Options();o2.inSampleSize = scale;fis = new FileInputStream(fileName);b = BitmapFactory.decodeStream(fis, null, o2);fis.close();} catch (IOException e) {} catch (OutOfMemoryError e) {System.gc();}return b;}
更多相关文章
- android为图片生成缩略图
- android 读取文件内容操作
- Android(安卓)在屏幕上打印LOG
- Android(安卓)Fresco图片处理库用法API英文原文文档2-1(Facebook
- 仿QQ android 实战(学习 android 先来个QQ)
- Android(安卓)SharedPreferences解析
- android shareperfence的存储更改与读取
- Android读写文件
- Android(安卓)图片阴影处理分析!