Android从SD卡和Res读取图片,防止发生OOM内存移除

 
 
       /**
	 * 从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读取SD卡图片,Android读取Res图片,防止OOM,防止内存移除)