【发布时间】:2016-04-16 21:32:45
【问题描述】:
我的程序批量处理一些图像。我目前需要读取图像的 exif 方向标签,将其旋转到正确的方向,进行一些处理并保存图像,而不使用任何 EXIF 方向标签,但具有正确的旋转。(或带有正确方向的 EXIF 标签)
我正在阅读 EXIF 并使用 this library 旋转:
var bmp = new Bitmap(pathToImageFile);
var exif = new EXIFextractor(ref bmp, "n"); // get source from http://www.codeproject.com/KB/graphics/exifextractor.aspx?fid=207371
if (exif["Orientation"] != null)
{
RotateFlipType flip = OrientationToFlipType(exif["Orientation"].ToString());
if (flip != RotateFlipType.RotateNoneFlipNone) // don't flip of orientation is correct
{
bmp.RotateFlip(flip);
bmp.Save(pathToImageFile, ImageFormat.Jpeg);
}
// Match the orientation code to the correct rotation:
private static RotateFlipType OrientationToFlipType(string orientation)
{
switch (int.Parse(orientation))
{
case 1:
return RotateFlipType.RotateNoneFlipNone;
case 2:
return RotateFlipType.RotateNoneFlipX;
case 3:
return RotateFlipType.Rotate180FlipNone;
case 4:
return RotateFlipType.Rotate180FlipX;
break;
case 5:
return RotateFlipType.Rotate90FlipX;
break;
case 6:
return RotateFlipType.Rotate90FlipNone;
case 7:
return RotateFlipType.Rotate270FlipX;
case 8:
return RotateFlipType.Rotate270FlipNone;
default:
return
}
}
这行得通。但是保存此图像时,exif 旋转标签仍然存在,这使图像方向错误。 我能做的是
var bmp = new Bitmap(OS.FileName);
var exif = new EXIFextractor(ref bmp, "n");
exif.setTag(0x112, "1");
bmp.save("strippedexifimage");
但是当在循环中使用这段代码时,我的程序会减慢 50% 左右。还有其他方法吗?可能是应用旋转后反旋转图像的代码,这行得通吗?
更新:
@Hans Passant 您的答案有效,但它产生的结果与图书馆产生的结果相同。当我使用 bitmap.save() 时,库和您的代码都有效。但是当我使用以下代码根据用户选择的格式保存图像时。 Imgformat 可以是imgformat = "image/png";,imgformat = "image/jpeg"; 等,一些图像仍然会使用错误的 exif 方向标签保存。即:我在 Windows 资源管理器中看到错误的图像预览,当我用 MS Paint 打开图像时,图像的方向正确。我做错了什么?请帮忙。
private void saveJpeg(string path, Bitmap img, long quality)
{
EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
ImageCodecInfo Codec = this.getEncoderInfo(imgformat);
if (Codec == null)
return;
EncoderParameters encoderParams = new EncoderParameters(1);
encoderParams.Param[0] = qualityParam;
img.Save(path + ext, Codec, encoderParams);
}
private ImageCodecInfo getEncoderInfo(string mimeType)
{
// Get image codecs for all image formats
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
// Find the correct image codec
for (int i = 0; i < codecs.Length; i++)
if (codecs[i].MimeType == mimeType)
return codecs[i];
return null;
}
【问题讨论】:
-
看看 ImageMagick。我认为它可以满足您的所有需求。您可以为它编写代码.. 或按原样使用它。 :)
标签: c# .net gdi+ exif system.drawing