获取图像方向并按方向旋转
使用以下代码获取图像方向时遇到问题
string fileName = @"D:\...\...\01012015004435.jpeg"; int rotate = 0; using (var image = System.Drawing.Image.FromFile(fileName)) { foreach (var prop in image.PropertyItems) { if (prop.Id == 0x112) { if (prop.Value[0] == 6) rotate = 90; if (prop.Value[0] == 8) rotate = -90; if (prop.Value[0] == 3) rotate = 180; prop.Value[0] = 1; } } }
在获得正确的方向后,我习惯像旋转图像一样
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; } }
但问题在于第一个代码
prop.Id
我总是[20625]
prop.Id == 20625
所以不满足条件每次请让我知道是否有任何问题或其他选择
谢谢
在其他答案和评论中可能有足够的信息将这些全部放在一起,但这是一个有效的代码示例。
此扩展方法将采用System.Drawing
Image
,读取其Exif Orientation标记(如果存在),并翻转/旋转它(如果需要)。
private const int exifOrientationID = 0x112 //274 public static void ExifRotate(this Image img) { if (!img.PropertyIdList.Contains(exifOrientationID)) return; var prop = img.GetPropertyItem(exifOrientationID); int val = BitConverter.ToUInt16(prop.Value, 0); var rot = RotateFlipType.RotateNoneFlipNone; if (val == 3 || val == 4) rot = RotateFlipType.Rotate180FlipNone; else if (val == 5 || val == 6) rot = RotateFlipType.Rotate90FlipNone; else if (val == 7 || val == 8) rot = RotateFlipType.Rotate270FlipNone; if (val == 2 || val == 4 || val == 5 || val == 7) rot |= RotateFlipType.RotateNoneFlipX; if (rot != RotateFlipType.RotateNoneFlipNone) img.RotateFlip(rot); }
使用以下内容:
-
img.PropertyIdList.Contains(orientationId)
检查是否存在Exif标记。 - 获取它的
img.GetPropertyItem(orientationId)
(在上面的检查之后,否则你将得到一个ArgumentException
)。 -
img.SetPropertyItem(pItem)
来设置它。
我写了一个简单的帮助器类来完成所有这些:你可以在这里查看完整的源代码 。
其他信息和快速案例研究也可以在我的博客上的以下post中找到:
在.NET C中更改iPhone和/或Android图片的图像方向
您可以使用此链接http://regex.info/exif.cgi来检查图像嵌入的元数据。 如果在EXIF表中未找到“0x0112”,则图像不包含rotation属性。