2013-12-22 130 views
2

我正在創建一個打開照片庫的應用程序,通過從圖庫中選擇該照片,照片將顯示在另一個活動中。我的問題是,我在肖像模式下拍攝的照片將在顯示後旋轉。但是我在橫向模式下拍攝的照片將會正確顯示。如何檢查在android中使用攝像頭在縱向模式還是橫向模式下拍攝圖像?

這就是爲什麼,我必須檢查是否在縱向模式或橫向模式下使用android中的相機拍攝圖像,以便我可以旋轉拍攝的人像照片。任何人都可以幫助我如何做到這一點?

N.B .:縱向拍攝圖像和橫向拍攝圖像的寬度和高度相同。

+1

你檢查ExifInterface這裏解釋呢? http://stackoverflow.com/questions/11026615/captured-photo-orientation-is-changing-in-android – fasteque

+0

不,我沒有... – CrazyLearner

回答

2

您可以隨時使用矩陣檢查圖像的旋轉並相應地旋轉它。

此代碼放在onActivityResult - >

BitmapFactory.Options bmOptions = new BitmapFactory.Options(); 
    bmOptions.inJustDecodeBounds = false; 
    bmOptions.inPurgeable = true; 

     Bitmap cameraBitmap = BitmapFactory.decodeFile(filePath);//get file path from intent when you take iamge. 
     ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
     cameraBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos); 


     ExifInterface exif = new ExifInterface(filePath); 
     float rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); 
     System.out.println(rotation); 

     float rotationInDegrees = exifToDegrees(rotation); 
     System.out.println(rotationInDegrees); 

     Matrix matrix = new Matrix(); 
     matrix.postRotate(rotationInDegrees); 

     Bitmap scaledBitmap = Bitmap.createBitmap(cameraBitmap); 
     Bitmap rotatedBitmap = Bitmap.createBitmap(cameraBitmap , 0, 0, scaledBitmap .getWidth(), scaledBitmap .getHeight(), matrix, true); 
     FileOutputStream fos=new FileOutputStream(filePath); 
     rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos); 
     fos.flush(); 
     fos.close(); 

OnActivityResult代碼到此爲止。

下面這個函數是用來獲取旋轉: -

private static float exifToDegrees(float exifOrientation) {   
    if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) { return 90; } 
    else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) { return 180; } 
    else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) { return 270; }    
    return 0;  
} 
相關問題