2017-03-03 77 views
0

我正在嘗試適應微軟的projectOxford EmotionApi的圖像自動旋轉代碼。分析設備攝像機拍攝的每個圖像的角度,然後旋轉到正確的橫向視圖,以通過情緒API進行分析。旋轉位圖而不使用ImageURI/ContentResolver?

我的問題是:我將如何調整下面的代碼以將位圖作爲參數?在這種情況下,我也完全失去了內容解析器和ExitInterface的角色。任何幫助,非常感謝。

private static int getImageRotationAngle(
     Uri imageUri, ContentResolver contentResolver) throws IOException { 
    int angle = 0; 
    Cursor cursor = contentResolver.query(imageUri, 
      new String[] { MediaStore.Images.ImageColumns.ORIENTATION }, null, null, null); 
    if (cursor != null) { 
     if (cursor.getCount() == 1) { 
      cursor.moveToFirst(); 
      angle = cursor.getInt(0); 
     } 
     cursor.close(); 
    } else { 
     ExifInterface exif = new ExifInterface(imageUri.getPath()); 
     int orientation = exif.getAttributeInt(
       ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); 

     switch (orientation) { 
      case ExifInterface.ORIENTATION_ROTATE_270: 
       angle = 270; 
       break; 
      case ExifInterface.ORIENTATION_ROTATE_180: 
       angle = 180; 
       break; 
      case ExifInterface.ORIENTATION_ROTATE_90: 
       angle = 90; 
       break; 
      default: 
       break; 
     } 
    } 
    return angle; 
} 

// Rotate the original bitmap according to the given orientation angle 
private static Bitmap rotateBitmap(Bitmap bitmap, int angle) { 
    // If the rotate angle is 0, then return the original image, else return the rotated image 
    if (angle != 0) { 
     Matrix matrix = new Matrix(); 
     matrix.postRotate(angle); 
     return Bitmap.createBitmap(
       bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); 
    } else { 
     return bitmap; 
    } 
} 

回答

0

我會如何適應下面的代碼,以位圖作爲參數?

你不行。

我也完全失去了作爲內容Resolver和ExitInterface在這種情況下

在你的問題中的代碼使用EXIF Orientation標籤,以確定應適用於該方位的作用圖像,照相機所拍攝的照片(或任何設置標籤)報告。 ExifInterface是讀取EXIF標籤的代碼。 ExifInterface需要使用實際的JPEG數據,而不是解碼的Bitmap — a Bitmap不再具有EXIF標籤。

ContentResolver這裏的代碼存在bug並且不應該使用。 com.android.support:exifinterface庫中的ExifInterface具有一個構造函數,它需要一個InputStream,從中讀取JPEG。在這裏使用Uri的正確方法是將它傳遞給ContentResolver上的openInputStream(),將該流傳遞給ExifInterface構造函數。

+0

瞭解,謝謝你的詳細解釋。任何關於旋轉位圖的建議? –

+0

@ A.Xu:嗯,你的問題中的'rotateBitmap()'方法將旋轉位圖。整個EXIF標題背後的要點是確定是否應該旋轉JPEG,如果是,則確定是否應該旋轉多少。 – CommonsWare