1. 程式人生 > >使用Bitmap將自身儲存為檔案,BitmapFactory從File中解析圖片並防止OOM

使用Bitmap將自身儲存為檔案,BitmapFactory從File中解析圖片並防止OOM

/** 獲得與需要的比例最接近的比例 */
	static int calculateInSampleSize(BitmapFactory.Options bitmapOptions, int reqWidth, int reqHeight) {
		final int height = bitmapOptions.outHeight;
		final int width = bitmapOptions.outWidth;
		int sampleSize = 1;
		if (height > reqHeight || width > reqWidth) {
			final int heightRatio = Math.round((float) height / (float) reqHeight);
			final int widthRatio = Math.round((float) width / (float) reqWidth);
			sampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
		}
		return sampleSize;
	}
	
	public static Bitmap decodeImage(String filePath) {
		/** Decode image size */
		BitmapFactory.Options o = new BitmapFactory.Options();
		/** 只取寬高防止oom */
		o.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(filePath, o);

		int scale=calculateInSampleSize(o, displayStats.maxItemWidthHeight, displayStats.maxItemWidthHeight);

		BitmapFactory.Options options=new BitmapFactory.Options();
		/** Decode with inSampleSize,比直接算出options中的使用更少的記憶體*/
		options.inSampleSize=scale;
		/** 記憶體不足的時候可被擦除 */
		options.inPurgeable = true;
		/** 深拷貝 */
		options.inInputShareable = true;

		synchronized (DDGControlVar.DECODE_LOCK) {
			Bitmap result = BitmapFactory.decodeFile(filePath, options);
			return result;
		}
	}