2010-08-03 76 views
4

有多頁面tiff,我想從這個Tiff文件中提取頁面[n]/frame [n]並保存。從多頁面提取幀tiff - c#

如果我多頁TIFF有3架,之後我提取一個頁/幀 - 我想留下具有2頁/幀的並且具有

1圖像

1圖像只有1頁/幀。

回答

6

下面是一些代碼,用於將多幀tiff中的最後一幀保存爲單頁tiff文件。 (爲了使用此代碼,您需要添加對PresentationCore.dll的引用)。

Stream imageStreamSource = new FileStream(imageFilename, FileMode.Open, FileAccess.Read, FileShare.Read); 
     MemoryStream memstream = new MemoryStream(); 
     memstream.SetLength(imageStreamSource.Length); 
     imageStreamSource.Read(memstream.GetBuffer(), 0, (int)imageStreamSource.Length); 
     imageStreamSource.Close(); 

     BitmapDecoder decoder = TiffBitmapDecoder.Create(memstream,BitmapCreateOptions.PreservePixelFormat,BitmapCacheOption.Default); 

     Int32 frameCount = decoder.Frames.Count; 

     BitmapFrame imageFrame = decoder.Frames[0]; 

     MemoryStream output = new MemoryStream(); 
     TiffBitmapEncoder encoder = new TiffBitmapEncoder(); 
     encoder.Frames.Add(imageFrame); 
     encoder.Save(output); 

     FileStream outStream = File.OpenWrite("Image.Tiff"); 
     output.WriteTo(outStream); 
     outStream.Flush(); 
     outStream.Close(); 
     output.Flush(); 
     output.Close(); 
+1

爲了使用此代碼,你需要添加一個引用您也可以在「[程序文件] /引用程序」文件夾中找到的PresentationCore.dll中。此程序集包含'System.Windows.Media.Imaging'命名空間。 – Crackerjack 2011-07-13 22:27:06

1
public void SaveFrame(string path, int frameIndex, string toPath) 
    { 
     using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) 
     { 
      BitmapDecoder dec = BitmapDecoder.Create(stream, BitmapCreateOptions.IgnoreImageCache, BitmapCacheOption.None); 
      BitmapEncoder enc = BitmapEncoder.Create(dec.CodecInfo.ContainerFormat); 

      enc.Frames.Add(dec.Frames[frameIndex]); 

      using (FileStream tmpStream = new FileStream(toPath, FileMode.Create)) 
      { 
       enc.Save(tmpStream); 
      } 
     } 
    }