如果没有原始图像数据,就无法确定发生了什么。但很明显,在某些时候,一些涉及图像处理的软件已经使用 EXIF 方向属性来旋转图像,而不是实际修改图像数据本身。这可能是照片查看器或在某个时间点处理照片的其他工具。
以下代码可用于检测图像的方向,由拍摄照片的相机记录在 EXIF 数据中:
static ImageOrientation GetOrientation(this Image image)
{
PropertyItem pi = SafeGetPropertyItem(image, 0x112);
if (pi == null || pi.Type != 3)
{
return ImageOrientation.Original;
}
return (ImageOrientation)BitConverter.ToInt16(pi.Value, 0);
}
// A file without the desired EXIF property record will throw ArgumentException.
static PropertyItem SafeGetPropertyItem(Image image, int propid)
{
try
{
return image.GetPropertyItem(propid);
}
catch (ArgumentException)
{
return null;
}
}
地点:
/// <summary>
/// Possible EXIF orientation values describing clockwise
/// rotation of the captured image due to camera orientation.
/// </summary>
/// <remarks>Reverse/undo these transformations to display an image correctly</remarks>
public enum ImageOrientation
{
/// <summary>
/// Image is correctly oriented
/// </summary>
Original = 1,
/// <summary>
/// Image has been mirrored horizontally
/// </summary>
MirrorOriginal = 2,
/// <summary>
/// Image has been rotated 180 degrees
/// </summary>
Half = 3,
/// <summary>
/// Image has been mirrored horizontally and rotated 180 degrees
/// </summary>
MirrorHalf = 4,
/// <summary>
/// Image has been mirrored horizontally and rotated 270 degrees clockwise
/// </summary>
MirrorThreeQuarter = 5,
/// <summary>
/// Image has been rotated 270 degrees clockwise
/// </summary>
ThreeQuarter = 6,
/// <summary>
/// Image has been mirrored horizontally and rotated 90 degrees clockwise.
/// </summary>
MirrorOneQuarter = 7,
/// <summary>
/// Image has been rotated 90 degrees clockwise.
/// </summary>
OneQuarter = 8
}
上面的GetOrientation() 方法是作为扩展方法编写的,当然你也可以把它称为普通的静态方法。无论哪种方式,只需将您刚刚从文件中打开的 Bitmap 对象传递给它,它就会返回存储在文件中的 EXIF 方向(如果有)。
有了它,您可以根据需要旋转图像。