1. 程式人生 > >Android拍照、攝像方向旋轉的問題 代碼具體解釋

Android拍照、攝像方向旋轉的問題 代碼具體解釋

void window bean ken cas style 角度 port n)

近期做了個拍照、攝像的應用。遇到了拍照、攝像的圖像相對於現實。翻轉了90度。原因:相機這個硬件的角度是橫屏的角度,所以會出現都是橫屏的。

1.照相、攝影預覽圖像的正確角度顯 示:

    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);
    }

改方法動態獲取手機是Landscape(橫屏)或Portrait(豎屏)來更改預覽圖。

(後屏的cameraId是0 )

2.圖像保存的正確角度(當我們拍下照片,發現角度又不正確)

@Override
public void onPictureTaken(byte[] data, Camera camera) {

	        try {
	                  Bitmap realImage = BitmapFactory.decodeByteArray(data, 0, data.length);
	                  android.hardware.Camera.CameraInfo info = new android.hardware.Camera.CameraInfo();
	                  android.hardware.Camera.getCameraInfo(0, info);
	                  Bitmap bitmap = rotate(realImage, info.orientation);

	                  FileOutputStream fos = new FileOutputStream(pictureFile);               
	                  bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
	                  fos.close();                
	        	
//	            FileOutputStream fos = new FileOutputStream(pictureFile);
//	            fos.write(data);
//	            fos.close();
	            
	            DBRecordAdapter.getInstance().insertRecord(bean);
	        } catch (FileNotFoundException e) {
	            Log.d(TAG, "File not found: " + e.getMessage());
	        } catch (IOException e) {
	            Log.d(TAG, "Error accessing file: " + e.getMessage());
	        }
}

3.錄像回放的正確的方向:

		mMediaRecorder.setOrientationHint(90);
該方法在prepare()之前調用。


Android拍照、攝像方向旋轉的問題 代碼具體解釋