也许是因为图像物理存储的方向与显示的方向不同,例如,用相机横向拍摄的 640*480 镜头可能会存储为 480*640,并带有方向 exif 数据标志。
这很棒,因为资源管理器/绘画/Photoshop/几乎每个观看者都会看到该 exif 标志并在渲染之前旋转它。但是,.net Image 类不会(当您知道发生了什么时,这似乎是合理的),因此您必须在新的缩略图上设置 exif 旋转属性(我不喜欢这样做,只是因为我不喜欢缩略图上有任何属性)或自己检查并旋转缩略图。
下面是执行此操作的粗略方法。请注意,我提供了 C# 代码作为您引用的答案的修改版本,因为这也是 C# 的。转换到 vb.net 应该非常简单:)
if (sourceImage.PropertyIdList.Contains(0x112)) //0x112 = Orientation
{
var prop = sourceImage.GetPropertyItem(0x112);
if (prop.Type == 3 && prop.Len == 2)
{
UInt16 orientationExif = BitConverter.ToUInt16(sourceImage.GetPropertyItem(0x112).Value, 0);
if (orientationExif == 8)
{
newImage.RotateFlip(RotateFlipType.Rotate270FlipNone);
}
else if (orientationExif == 3)
{
newImage.RotateFlip(RotateFlipType.Rotate180FlipNone);
}
else if (orientationExif == 6)
{
newImage.RotateFlip(RotateFlipType.Rotate90FlipNone);
}
}
}
所以更新后的FixedSize代码将是这样的:
static Image FixedSize(Image imgPhoto, int Width, int Height)
{
int sourceWidth = imgPhoto.Width;
int sourceHeight = imgPhoto.Height;
int sourceX = 0;
int sourceY = 0;
int destX = 0;
int destY = 0;
float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;
nPercentW = ((float)Width / (float)sourceWidth);
nPercentH = ((float)Height / (float)sourceHeight);
if (nPercentH < nPercentW)
{
nPercent = nPercentH;
destX = System.Convert.ToInt16((Width -
(sourceWidth * nPercent)) / 2);
}
else
{
nPercent = nPercentW;
destY = System.Convert.ToInt16((Height -
(sourceHeight * nPercent)) / 2);
}
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);
Bitmap bmPhoto = new Bitmap(Width, Height,
PixelFormat.Format24bppRgb);
bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
imgPhoto.VerticalResolution);
Graphics grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.Clear(Color.Red);
grPhoto.InterpolationMode =
InterpolationMode.HighQualityBicubic;
grPhoto.DrawImage(imgPhoto,
new Rectangle(destX, destY, destWidth, destHeight),
new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
GraphicsUnit.Pixel);
grPhoto.Dispose();
//Rotate image to what is expected.
if (imgPhoto.PropertyIdList.Contains(0x112)) //0x112 = Orientation
{
var prop = imgPhoto.GetPropertyItem(0x112);
if (prop.Type == 3 && prop.Len == 2)
{
UInt16 orientationExif = BitConverter.ToUInt16(sourceImage.GetPropertyItem(0x112).Value, 0);
if (orientationExif == 8)
{
bmPhoto.RotateFlip(RotateFlipType.Rotate270FlipNone);
}
else if (orientationExif == 3)
{
bmPhoto.RotateFlip(RotateFlipType.Rotate180FlipNone);
}
else if (orientationExif == 6)
{
bmPhoto.RotateFlip(RotateFlipType.Rotate90FlipNone);
}
}
}
return bmPhoto;
}
请注意,这并不涵盖所有 exif 方向,仅涵盖常见的方向。
参考:
http://www.impulseadventure.com/photo/exif-orientation.html
http://msdn.microsoft.com/en-us/library/xddt0dz7.aspx
p.s:这是我的第一个堆栈溢出答案,所以请简单地对待反馈;)