如何使用原始编码保存图像

时间:2017-06-02 10:02:57

标签: c# .net image tiff image-formats

我在loading and saving images .net时遇到意外行为,仅使用内置System.Drawing命名空间的方法。

我的方式:
我有一张图片,我正在通过拨打System.Drawing.Image.FromStream()加载 在进行一些操作后,我必须使用Tagged Image File Format (TIFF)保存图像 - 我使用内置的.net方法来实现这一点:

private void doSomethingAndSave(System.Drawing.Image image, string destFile)
{
  //...doin something...

  //..save the image as Tiff
  image.Save(destFile, ImageFormat.Tiff);
}

这可以按预期工作 - 如果我通过阅读first 4Bytes来调查该文件,我会得到:

  

0x49 0x49 0x2a 0x20

成功识别TIFF-Image。到目前为止,这么好......

我面临的问题:
稍后在我的代码中我必须重新加载那些图像,也许还有一些来自其他来源,我不能指望它们被编码为TIFF,但我可以确保它们总是通过.net System.Drawing.Image.Save()创建。 /> 因此,不使用第三方程序/编码 我可能必须执行一些操作并将图像保存回磁盘 此时我想将图像保存在their same origin format

例如,我正在执行以下操作:

public void RotateImage(string file)
{
   using(var img = System.Drawing.Image.FromFile(file))
   {
     img.RotateFlip(System.Drawing.RotateFlipType.Rotate270FlipNone);
     img.Save(file);
   }
}

但是现在,如果我调查该文件,我可以看到格式已经转换为PNG,现在是第一个8Bytes:

  

0x89 0x50 0x4E 0x47 0x0D 0x0A 0x1A 0x0A

所以Tiff - 图片“已转换”PNG文件。 我默认情况下无法提供imageFormat ImageFormat.Tiff参数,因为原始文件is not a TIFF可能编码一个 - 我必须保留原始格式!

我尝试手动应用源ImageFormat :(最终也会出现在PNG文件中)

public void RotateImage(string file)
{
  using(var img = System.Drawing.Image.FromFile(file))
  {
    var imageFormat = img.RawFormat;
    img.RotateFlip(System.Drawing.RotateFlipType.Rotate270FlipNone);
    img.Save(file, imageFormat);
  }
}

可能是因为RawFormat中不存在ImageCodecInfo.GetImageDecoders() ... 我之所以这样,是因为:
另一种方法是评估编码并应用于保存:

 public void PerfomOperation(string fileName)
 {
   using (var img = System.Drawing.Image.FromFile(fileName))
   {
     Imaging.EncoderValue format = imaging.EncoderValue.CompressionLZW;
     var codecInfo = this.GetImageCodecInfo(img);
     Imaging.Encoder enc = Imaging.Encoder.Compression;
     Imaging.EncoderParameters ep = new Imaging.EncoderParameters(1);
     ep.Param[0] = new Imaging.EncoderParameter(enc, (long)format);

     img.Save(fileName, codecInfo, ep);
   }
 }

public ImageCodecInfo GetImageCodecInfo(System.Drawing.Image image)
{
  var imgguid = image.RawFormat.Guid;
  foreach (ImageCodecInfo codec in ImageCodecInfo.GetImageDecoders())
  {
       if (codec.FormatID == imgguid)
           return codec;
  }
  return null;  // "image/unknown";
}

Guid{b96b3caa-0728-11d3-9d7b-0000f81ef32e} <{>}中的Image.RawFormat ImageCodecInfo不存在 < - {>} - 尽管我使用的是默认.net方法Save(image, ImageFormat.Tiff);之前!
所以我认为我的机器上必须存在正确的编解码器......?

最后: 如何使用原始图像格式保存图像
(系统提供的.net格式很好)

0 个答案:

没有答案