Picture orientation from gallery/camera intent

Juhani picture Juhani · Dec 23, 2010 · Viewed 30.5k times · Source

I'm getting picture to my app from camera / gallery intent. In many phones picture that I read from the intent / Uri is already rotated to correct orientation. For example N1, Legend, Desire that is the case.

But then on some phones ( for example Milestone1, GalaxyS) the picture is always in landscape more no matter which way the picture was taken. This means that in my application portrait picture is presented wrong way to the user. I tried to read EXIF info of the picture but orientation tag is always 0. There has to be a way to find out the right orientation of the picture because in Milestone1 the gallery application shows the portrait pictures correctly.

How do I know if I need to rotate the picture myself before showing it to the user?

Thank you for you help!

Answer

eric.itzhak picture eric.itzhak · Jun 18, 2012

Florian answer is working for gallery images.

The following code works for captured images, havn't tried with gallery images but i believe it should work. Hope this helps anybody.

Code :

public static int getCameraPhotoOrientation(Context context, Uri imageUri, String imagePath){
     int rotate = 0;
     try {
         context.getContentResolver().notifyChange(imageUri, null);
         File imageFile = new File(imagePath);
         ExifInterface exif = new ExifInterface(
                 imageFile.getAbsolutePath());
         int orientation = exif.getAttributeInt(
                 ExifInterface.TAG_ORIENTATION,
                 ExifInterface.ORIENTATION_NORMAL);

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


         Log.v(TAG, "Exif orientation: " + orientation);
     } catch (Exception e) {
         e.printStackTrace();
     }
    return rotate;
 }

EDIT: As can be read in the comments, some devices do not support Exif information, havn't checked which but i think HTC doesn't. be sure to check what devices and create an alternative.