1. 程式人生 > >通過BitmapFactory.Options來縮放圖片

通過BitmapFactory.Options來縮放圖片

/**
	 * 縮放資源id為resId的圖片
	 * @param res
	 * @param resId 資源id
	 * @param reqWidth 縮放後的寬度
	 * @param reqHeight 縮放後的高度
	 * @return
	 */
	public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) {
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeResource(res, resId,options);

		options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
		options.inJustDecodeBounds=false;
			
		return BitmapFactory.decodeResource(res, resId,options);
	}

	/**
	 *計算inSampleSize
	 * @param options
	 * @param reqWidth 縮放後的寬度
	 * @param reqHeight 縮放後的高度
	 * @return
	 */
	private static int calculateInSampleSize(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 halfHeight = height / 2;
			final int halfWidth = width / 2;
			//計算inSampleSize直到縮放後的寬高都小於指定的寬高
			while ((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth) {
				inSampleSize *= 2;
			}

		}

		System.out.println(inSampleSize);
		return inSampleSize;
	}

使用時的程式碼如下: