Correct photo orientation using EXIF data with C#

When processing photos, sometimes you want to re-orient the photo according the orientation recorded by the camera (such as the iPhone’s accelerometer) and stored in the EXIF meta data.  It’s easy to do:

// Rotate the image according to EXIF data
var bmp = new Bitmap(pathToImageFile);
var exif = new EXIFextractor(ref bmp, "n"); // get source from http://www.codeproject.com/KB/graphics/exifextractor.aspx?fid=207371
 
if (exif["Orientation"] != null)
{
RotateFlipType flip = OrientationToFlipType(exif["Orientation"].ToString());
 
if (flip != RotateFlipType.RotateNoneFlipNone) // don't flip of orientation is correct
{
bmp.RotateFlip(flip);
exif.setTag(0x112, "1"); // Optional: reset orientation tag
bmp.Save(pathToImageFile, ImageFormat.Jpeg);
}
 
// Match the orientation code to the correct rotation:
 
private static RotateFlipType OrientationToFlipType(string orientation)
{
switch (int.Parse(orientation))
{
case 1:
return RotateFlipType.RotateNoneFlipNone;
break;
case 2:
return RotateFlipType.RotateNoneFlipX;
break;
case 3:
return RotateFlipType.Rotate180FlipNone;
break;
case 4:
return RotateFlipType.Rotate180FlipX;
break;
case 5:
return RotateFlipType.Rotate90FlipX;
break;
case 6:
return RotateFlipType.Rotate90FlipNone;
break;
case 7:
return RotateFlipType.Rotate270FlipX;
break;
case 8:
return RotateFlipType.Rotate270FlipNone;
break;
default:
return RotateFlipType.RotateNoneFlipNone;
}
}

5 thoughts on “Correct photo orientation using EXIF data with C#”

  1. Thanks – this saved me quite a bit of time today.
    Reset orientation code did not work for me – what gets written cannot be re-read by EXIFextractor. For me, this works

    int propertyId = 0x112;
    int propertyLen = 2;
    short propertyType = 3;
    byte[] propertyValue = { 1, 0 };
    exif.setTag(propertyId, propertyLen, propertyType, propertyValue);

    HTH

Leave a Reply