3
我想旋轉基於EXIF標記的圖像。我能夠成功處理圖像的旋轉,但在Windows資源管理器中的縮略圖仍然是顛倒的。打開圖像時絕對沒問題。已驗證修正的方向here.以下代碼的問題是,EXIF數據似乎沒有任何有關縮略圖方向的信息。我要的是:圖像旋轉但縮略圖不是
如果沒有可用的縮略圖方向,旋轉縮略圖和縮略圖定位更新圖像的元數據。
如果沒有可用的縮略圖方向信息,請旋轉縮略圖並添加縮略圖方向的圖像元數據。
我使用的代碼是:
public static RotateFlipType RotateImageByExifOrientationData(Image img, string oldFileName, string sourceFilePath, out string newFileName)
{
int orientationId = 0x0112;//Image orientation
int thumbnailOrientationId = 0x5029;//Thumbnail orientation
var fType = RotateFlipType.RotateNoneFlipNone;
if (img.PropertyIdList.Contains(orientationId))
{
var pItem = img.GetPropertyItem(orientationId);
//Get the orientation
fType = GetRotateFlipTypeByExifOrientationData(pItem.Value[0]);
if (fType != RotateFlipType.RotateNoneFlipNone)
{
img.RotateFlip(fType);
// Read orientation tag. Update to normal so that the other clients(image viewer or browser) will not rotate the rotated image.
// Force value to 1
pItem.Value = BitConverter.GetBytes((short)1);
img.SetPropertyItem(pItem);
PropertyItem thumbnailItem;
if (img.PropertyIdList.Contains(thumbnailOrientationId))
{
//If thumbnail metadata is available, update it.
thumbnailItem = img.GetPropertyItem(thumbnailOrientationId);
thumbnailItem.Value = BitConverter.GetBytes((short)1);
img.SetPropertyItem(thumbnailItem);
}
else
{
//If thumbnail metadata is not available, add appropriate metadata.
thumbnailItem = img.PropertyItems[0];
thumbnailItem.Id = thumbnailOrientationId;
thumbnailItem.Type = 2;
thumbnailItem.Value = BitConverter.GetBytes((short)1);
thumbnailItem.Len = thumbnailItem.Value.Length;
img.SetPropertyItem(thumbnailItem);
}
newFileName = "Rotated_" + oldFileName;
string targetFilePath = sourceFilePath + newFileName ;
ImageFormat targetFormat = ImageFormat.Jpeg;
img.Save(targetFilePath, targetFormat);
File.Delete(sourceFilePath + oldFileName);//Delete old file.
}
}
return fType;
}
我深深的懷疑是,縮略圖只是不遵循EXIF標籤,所以改變了EXIF元數據後,你必須重新生成縮略圖。 – mcepl