在作人臉識別的時候發現不少手機拍攝的圖像在C#讀取以後方向出現了錯誤,Bitmap中的寬度和實際的windows的文件屬性內的參數相反,引發一陣測試和思考,後來百度出來能夠用Exif來解決git
github有相關Exif介紹github
https://github.com/dlemstra/Magick.NET/blob/784e23b1f5c824fc03d4b95d3387b3efe1ed510b/Magick.NET/Core/Profiles/Exif/ExifTag.cswindows
維基百科也有說明測試
https://en.wikipedia.org/wiki/Exifspa
實際代碼是3d
/// <summary> /// 根據圖片exif調整方向 /// </summary> /// <param name="sm"></param> /// <returns></returns> public static Bitmap RotateImage(Stream sm) { Image img = Image.FromStream(sm); var exif = img.PropertyItems; byte orien = 0; var item = exif.Where(m => m.Id == 274).ToArray(); if (item.Length > 0) orien = item[0].Value[0]; switch (orien) { case 2: img.RotateFlip(RotateFlipType.RotateNoneFlipX);//horizontal flip break; case 3: img.RotateFlip(RotateFlipType.Rotate180FlipNone);//right-top break; case 4: img.RotateFlip(RotateFlipType.RotateNoneFlipY);//vertical flip break; case 5: img.RotateFlip(RotateFlipType.Rotate90FlipX); break; case 6: img.RotateFlip(RotateFlipType.Rotate90FlipNone);//right-top break; case 7: img.RotateFlip(RotateFlipType.Rotate270FlipX); break; case 8: img.RotateFlip(RotateFlipType.Rotate270FlipNone);//left-bottom break; default: break; } return (Bitmap)img; }