在做人脸识别的时候发现很多手机拍摄的图像在C#读取之后方向出现了错误,Bitmap中的宽度和实际的windows的文件属性内的参数相反,引起一阵测试和思考,后来百度出来可以用Exif来解决
github有相关Exif介绍
https://github.com/dlemstra/Magick.NET/blob/784e23b1f5c824fc03d4b95d3387b3efe1ed510b/Magick.NET/Core/Profiles/Exif/ExifTag.cs
维基百科也有说明
https://en.wikipedia.org/wiki/Exif
实际代码是
/// <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; }