2012-01-10 81 views

回答

12

您需要使用嵌入在照片中的EXIF標籤:

private int getExifOrientation() { 
    ExifInterface exif; 
    int orientation = 0; 
    try { 
    exif = new ExifInterface(mImagePath); 
    orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1); 
    } catch (IOException e) { 
    e.printStackTrace(); 
    } 
    Log.d(TAG, "got orientation " + orientation); 
    return orientation; 
} 

然而,返回的實際EXIF值幾分怪異。它允許各種旋轉和鏡像。我發現的最佳參考是here。一般情況下,你的方位後,你會希望通過查找功能來運行它,以獲得旋轉度:

private int getBitmapRotation() { 
    int rotation = 0; 
    switch (getExifOrientation()) { 
    case ExifInterface.ORIENTATION_ROTATE_180: 
     rotation = 180; 
     break; 
    case ExifInterface.ORIENTATION_ROTATE_90: 
     rotation = 90; 
     break; 
    case ExifInterface.ORIENTATION_ROTATE_270: 
     rotation = 270; 
     break; 
    } 

    return rotation; 
} 
+2

我得到錯誤「01-11 00:51:37.687:ERROR/JHEAD(7055):無法在該行打開'/file:/mnt/sdcard/.temp/photo1151619024.jpg'」exif = new ExifInterface (mImagePath);「 – StoneHeart 2012-01-10 17:52:22

+0

我確定該文件仍然存在,並且我已經在清單 – StoneHeart 2012-01-10 17:53:40

+2

/file中設置了權限android.permission.WRITE_EXTERNAL_STORAGE:/看起來不像路徑的適當部分...它可能只是/ mnt/sdcard/... – elijah 2012-01-10 18:05:51

1

您可以根據照片的高度和寬度確定方向嗎?如果它比它高,那就是風景。如果它比它寬,它是肖像。

如果它是方形的,那麼你將不得不讀取EXIF數據,並希望它爲這些圖像設置。 EXIF數據應該給定方位數據。

+0

沒有,它們的寬度和高度相同 – StoneHeart 2012-01-10 17:45:51

+0

尺寸不夠大 - 它可能是風景但是是倒置的,這取決於我是將手機向左還是向右轉到拍照。 – 2012-03-11 20:42:04

7

我正在尋找一個類似的解決我的問題。我正在從相機或畫廊拍攝照片,並將其轉換爲位圖以用於我的應用程序。問題是在PORTRAIT拍攝的照片正在旋轉-90度。

正在搜索答案我發現這個帖子和https://stackoverflow.com/a/11081918/3062284非常相似。我實際上使用了後者。但是,像@StoneHeart一樣,我正在讀取圖像路徑時發生錯誤。

我使用這個代碼在我的onActivityResult():

case CAMERA_REQUEST_CODE: 
if (resultCode == RESULT_OK); 
uriImage = data.getData(); 
ExifInterface exif = new ExifInterface(uriImage.getPath()); 

由於這個錯誤不是在以前的評論,我想我會分享我發現使用https://stackoverflow.com/a/10564727/3062284

我需要真正的解決方案解決從文章中使用此方法的文件的路徑。

 private String getRealPathFromURI(Uri contentUri) { 
     String[] proj = { MediaStore.Images.Media.DATA }; 
     CursorLoader loader = new CursorLoader(this, contentUri, proj, null, null, null); 
     Cursor cursor = loader.loadInBackground(); 
     int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 
     cursor.moveToFirst(); 
     return cursor.getString(column_index); 
    } 

和編輯我的代碼如下:

case CAMERA_REQUEST_CODE: 
if (resultCode == RESULT_OK); 
uriImage = data.getData(); 
String imagePath = getRealPathFromURI(uriImage); 
ExifInterface exif = new ExifInterface(imagePath); 

和固定的「jhead的不能打開文件」的錯誤我得到的。

+0

繁榮,你剛剛結束了我的2小時問題! – 2015-05-10 20:05:01

+0

JHead問題的最佳解決方案 – rookieDeveloper 2017-02-03 09:54:10