BLOG.CSHARPHELPER.COM: Use EXIF information to orient an image properly in C#
Use EXIF information to orient an image properly in C#
The example Read an image file's EXIF orientation data in C# shows how to read EXIF orientation information from an image. Using that information, it's easy to orient the image so it appears right side up.
This example uses the following code to orient an image.
// Orient the image properly. public static void OrientImage(Image img) { // Get the image's orientation. ExifOrientations orientation = ImageOrientation(img);
// Orient the image. switch (orientation) { case ExifOrientations.Unknown: case ExifOrientations.TopLeft: break; case ExifOrientations.TopRight: img.RotateFlip(RotateFlipType.RotateNoneFlipX); break; case ExifOrientations.BottomRight: img.RotateFlip(RotateFlipType.Rotate180FlipNone); break; case ExifOrientations.BottomLeft: img.RotateFlip(RotateFlipType.RotateNoneFlipY); break; case ExifOrientations.LeftTop: img.RotateFlip(RotateFlipType.Rotate90FlipX); break; case ExifOrientations.RightTop: img.RotateFlip(RotateFlipType.Rotate90FlipNone); break; case ExifOrientations.RightBottom: img.RotateFlip(RotateFlipType.Rotate90FlipY); break; case ExifOrientations.LeftBottom: img.RotateFlip(RotateFlipType.Rotate270FlipNone); break; }
// Set the image's orientation to TopLeft. SetImageOrientation(img, ExifOrientations.TopLeft); }
// Set the image's orientation. public static void SetImageOrientation(Image img, ExifOrientations orientation) { // Get the index of the orientation property. int orientation_index = Array.IndexOf(img.PropertyIdList, OrientationId);
// If there is no such property, do nothing. if (orientation_index < 0) return;
// Set the orientation value. PropertyItem item = img.GetPropertyItem(OrientationId); item.Value[0] = (byte)orientation; img.SetPropertyItem(item); }
The OrientImage method calls the ImageOrientation method described in the earlier example to see how the image is oriented. It then calls the Image class's RotateFlip method to rotate and flip the image so it is right side up. It finishes by calling the SetImageOrientation method to make the Image object's orientation TopLeft, the normal right side up orientation.
The SetImageOrientation method find the index of the image's orientation ID property. If that ID is present, the method gets its PropertyItem, sets the item's Value to the new orientation, and then uses the Image object's SetPropertyItem method to set the new value.
Comments