Created
November 16, 2018 16:13
-
-
Save howellcc/bb3ed8cfe6fd02b4947e727dc6177273 to your computer and use it in GitHub Desktop.
Rotate Image by Exif Data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static byte[] RotateImageByExifData(byte[] imgDataBytes, bool updateExifData = true) | |
{ | |
try | |
{ | |
using(MemoryStream origImageStream = new MemoryStream(imgDataBytes)) | |
{ | |
using(MemoryStream rotatedImageStream = new MemoryStream()) | |
{ | |
using(Image image = Image.FromStream(origImageStream, false, false)) | |
{ | |
ImageFormat originalFormat = image.RawFormat; | |
int orientationPropertyID = 0x0112; | |
if(image.PropertyIdList.Contains(orientationPropertyID)) | |
{ | |
PropertyItem orientationProperty = image.GetPropertyItem(orientationPropertyID); | |
RotateFlipType flipType = GetRotateFlipType(orientationProperty.Value[0]); | |
if(flipType != RotateFlipType.RotateNoneFlipNone) | |
{ | |
image.RotateFlip(flipType); | |
if(updateExifData) | |
{ | |
image.RemovePropertyItem(orientationPropertyID); | |
} | |
image.Save(rotatedImageStream, originalFormat); | |
imgDataBytes = rotatedImageStream.ToArray(); | |
} | |
} | |
} | |
} | |
} | |
} | |
catch(Exception ex) | |
{ | |
//Fail silently, but record. | |
System.Diagnostics.Debug.WriteLine(ex.Message); | |
} | |
return imgDataBytes; | |
} | |
public static RotateFlipType GetRotateFlipType(int orientation) | |
{ | |
switch(orientation) | |
{ | |
case 1: | |
default: | |
return RotateFlipType.RotateNoneFlipNone; | |
case 2: | |
return RotateFlipType.RotateNoneFlipX; | |
case 3: | |
return RotateFlipType.Rotate180FlipNone; | |
case 4: | |
return RotateFlipType.Rotate180FlipX; | |
case 5: | |
return RotateFlipType.Rotate90FlipX; | |
case 6: | |
return RotateFlipType.Rotate90FlipNone; | |
case 7: | |
return RotateFlipType.Rotate270FlipX; | |
case 8: | |
return RotateFlipType.Rotate270FlipNone; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment