Tag Archives: EXIF

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;
}
}