Get Image Orientation and rotate as per orientation

There's probably enough information in the other answers and comments to put this all together, but here's a working code example.

This extension method will take a System.Drawing Image, read its Exif Orientation tag (if present), and flip/rotate it (if necessary).

private const int exifOrientationID = 0x112; //274

public static void ExifRotate(this Image img)
{
    if (!img.PropertyIdList.Contains(exifOrientationID))
        return;

    var prop = img.GetPropertyItem(exifOrientationID);
    int val = BitConverter.ToUInt16(prop.Value, 0);
    var rot = RotateFlipType.RotateNoneFlipNone;

    if (val == 3 || val == 4)
        rot = RotateFlipType.Rotate180FlipNone;
    else if (val == 5 || val == 6)
        rot = RotateFlipType.Rotate90FlipNone;
    else if (val == 7 || val == 8)
        rot = RotateFlipType.Rotate270FlipNone;

    if (val == 2 || val == 4 || val == 5 || val == 7)
        rot |= RotateFlipType.RotateNoneFlipX;

    if (rot != RotateFlipType.RotateNoneFlipNone)
        img.RotateFlip(rot);
}

Use the following:

  • img.PropertyIdList.Contains(orientationId) to check if the Exif tag is present.
  • img.GetPropertyItem(orientationId) to get it (after the above check, otherwise you'll get an ArgumentException).
  • img.SetPropertyItem(pItem) to set it.

I wrote a simple helper class that does all that: you can check the full source code here.

Other info and a quick case-study is also available on the following post on my blog:

Change image orientation for iPhone and/or Android pics in NET C#