我的程序批量处理一些图像。我目前需要读取图像的exif方向标签,将其旋转到正确的方向,进行一些处理并保存图像,不带任何EXIF方向标签,但具有正确的旋转(或带有正确方向的EXIF标签)。
我正在使用这个库来读取EXIF并进行旋转:这个库。
但是,当我在循环中使用这段代码时,我的程序速度会减慢约50%。有没有其他的方法?也许可以在应用旋转后编写反向旋转图像的代码,那样行吗?
更新: @Hans Passant您的答案有效,但它产生的结果与库产生的结果相同。当我使用bitmap.save()时,库和您的代码都有效。但是,当我使用以下代码保存我的图像,具体取决于用户选择的格式。Imgformat可以是
我正在使用这个库来读取EXIF并进行旋转:这个库。
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可以是
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;
}