PictureBox和普通位图对象没有考虑EXIF Orientation Tag.Most现代相机现在将EXIF信息添加到Images.Im使用以下自定义函数来解决这个问题
Image FixImageOrientation(Image srce)
{
const int ExifOrientationId = 0x112;
// Read orientation tag
if (!srce.PropertyIdList.Contains(ExifOrientationId)) return srce;
var prop = srce.GetPropertyItem(ExifOrientationId);
var orient = BitConverter.ToInt16(prop.Value, 0);
// Force value to 1
prop.Value = BitConverter.GetBytes((short)1);
srce.SetPropertyItem(prop);
// Rotate/flip image according to <orient>
switch (orient)
{
case 1:
srce.RotateFlip(RotateFlipType.RotateNoneFlipNone);
return srce;
case 2:
srce.RotateFlip(RotateFlipType.RotateNoneFlipX);
return srce;
case 3:
srce.RotateFlip(RotateFlipType.Rotate180FlipNone);
return srce;
case 4:
srce.RotateFlip(RotateFlipType.Rotate180FlipX);
return srce;
case 5:
srce.RotateFlip(RotateFlipType.Rotate90FlipX);
return srce;
case 6:
srce.RotateFlip(RotateFlipType.Rotate90FlipNone);
return srce;
case 7:
srce.RotateFlip(RotateFlipType.Rotate270FlipX);
return srce;
case 8:
srce.RotateFlip(RotateFlipType.Rotate270FlipNone);
return srce;
default:
srce.RotateFlip(RotateFlipType.RotateNoneFlipNone);
return srce;
}
}
以上代码无法正常工作,除非我从文件路径
继续创建新的位图image = (Bitmap)FixImageOrientation(Bitmap.FromFile(path));
如果我像这样使用
image = (Bitmap)FixImageOrientation(myimage);
它不起作用!我做错了什么?我怎样才能解决这个问题?还有其他更好的方法吗?