android中Camera setDisplayOrientation使用

在寫相機相關應用的時候遇到捕獲的畫面方向和手機的方向不一致的問題,比如手機是豎着拿的,但是畫面是橫的,這是由於攝像頭默認捕獲的畫面byte[]是根據橫向來的,而你的應用是豎向的,解決辦法是調用setDisplayOrientation來設置PreviewDisplay的方向,效果就是將捕獲的畫面旋轉多少度顯示。
設置 preview 的順時針旋轉角度。這將影響 preview frames和拍照之後的相片顯示。該方法主要用於垂直模式的應用。注意在旋轉之前, front-facing cameras 的 preview顯示是水平 flip 的,這就是說, image 是沿着 camera sensor 的垂直中心軸來反射的。所以用戶可以像照鏡子一樣看到他們自己。這不會影響傳入函數 onPreviewFrame(byte[], Camera) 的、JPEG 相片的、或記錄的 video 的 byte array 的順序,你可以自己做旋轉處理。在preview 期間是不允許調用該方法的。如果你想要是你的照片和顯示出來的角度一致,你可以參考下列代碼:

public static void setCameraDisplayOrientation (Activity activity, int cameraId, android.hardware.Camera camera) {
	android.hardware.Camera.CameraInfo info = new android.hardware.Camera.CameraInfo();
	android.hardware.Camera.getCameraInfo (cameraId , info);
	int rotation = activity.getWindowManager ().getDefaultDisplay ().getRotation ();
	int degrees = 0;
	switch (rotation) {
		case Surface.ROTATION_0:
			degrees = 0;
			break;
		case Surface.ROTATION_90:
			degrees = 90;
			break;
		case Surface.ROTATION_180:
			degrees = 180;
			break;
		case Surface.ROTATION_270:
			degrees = 270;
			break;
	}
	int result;
	if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
		result = (info.orientation + degrees) % 360;
		result = (360 - result) % 360;   // compensate the mirror
	} else {
		// back-facing
		result = ( info.orientation - degrees + 360) % 360;
	}
	camera.setDisplayOrientation (result);
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章