MemoryStream.CopyTo不工作

TiffBitmapDecoder decoder = new TiffBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); using (MemoryStream allFrameStream = new MemoryStream()) { foreach (BitmapFrame frame in decoder.Frames) { using (MemoryStream ms= new MemoryStream()) { JpegBitmapEncoder enc = new JpegBitmapEncoder(); enc.Frames.Add(BitmapFrame.Create(frame)); enc.Save(ms); ms.CopyTo(allFrameStream); } } Document documentPDF = new Document(); PdfWriter writer = PdfWriter.GetInstance(documentPDF, allFrameStream); } 

始终allFrameStream的Length=0 。 但每次迭代我都能看到ms.Length=989548 。 我的代码中的错误是什么。 为什么ms.CopyTo(allFrameStream)不起作用?

填充后,将ms Position重置为0:

 enc.Save(ms); ms.Position = 0; ms.CopyTo(allFrameStream); 

来自Stream.CopyTo

复制从当前流中的当前位置开始

尝试执行allFrameStream.Position = 0; 就在写入PDF之前。

写入ms后, ms的位置结束。 你必须寻找流的开头,例如:

 ms.Seek(0,System.IO.SeekOrigin.Begin); 

之后ms.CopyTo正常工作。