尝试将多个tiff文件合并为单个多页tiff文件

时间:2019-07-26 21:24:13

标签: c# file merge tiff

我试图使用tiffbitmapencoder对象流化不同的tiff文件,并尝试创建单个多页tiff文档...使用下面的代码,我最终得到的是最后一个文件的最后一页,而不是所有文件的总页数

var filenames = new List<string>{"File1.tif", "File2.tif","File3.tif" };
using (Stream output = new FileStream("MergeSample.tif",
            FileMode.OpenOrCreate))
{
    foreach (var filename in filenames)
    {
         Stream imageStreamSource = new FileStream(filename, FileMode.Open,FileAccess.Read, FileShare.Read);
         TiffBitmapDecoder decoder = new TiffBitmapDecoder(imageStreamSource,
                    BitmapCreateOptions.PreservePixelFormat,
                    BitmapCacheOption.Default);
          foreach (BitmapFrame frame in decoder.Frames)
          {
              using (MemoryStream outStream = new MemoryStream())
              {
                  TiffBitmapEncoder enc = new TiffBitmapEncoder();
                  enc.Frames.Add(BitmapFrame.Create(frame));
                  enc.Save(output); //It overrides and finally i get the last image only
             //  outStream.CopyTo(output); this also not working.       
              }
          }
     }
}

能不能指导或指出步骤中错误的代码

1 个答案:

答案 0 :(得分:0)

在对TIFF进行故障排除之前,请尝试为第一个foreach包括适当的代码块。通过这种方式,我的意思是您可能希望在这段代码的大部分内容中使用花括号。

var filenames = new List<string>{"File1.tif", "File2.tif","File3.tif" };
using (Stream output = new FileStream("MergeSample.tif",
            FileMode.OpenOrCreate))
{
  foreach (var filename in filenames)
  {
    Stream imageStreamSource = new FileStream(filename, FileMode.Open,
                    FileAccess.Read, FileShare.Read);
    TiffBitmapDecoder decoder = new TiffBitmapDecoder(imageStreamSource,
                    BitmapCreateOptions.PreservePixelFormat,
                    BitmapCacheOption.Default);
    foreach (BitmapFrame frame in decoder.Frames)
    {
      using (MemoryStream outStream = new MemoryStream())
      {
         TiffBitmapEncoder enc = new TiffBitmapEncoder();
         enc.Frames.Add(BitmapFrame.Create(frame));
         enc.Save(output); //It overrides and finally i get the last image only
         //  outStream.CopyTo(output); this also not working.       
      }
    }
  }
}