简体   繁体   English

MemoryStream.CopyTo不工作

[英]MemoryStream.CopyTo Not working

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);
}

Always allFrameStream's Length=0 . 始终allFrameStream的Length=0 But each iteration I could see ms.Length=989548 . 但每次迭代我都能看到ms.Length=989548 What is the error in my code. 我的代码中的错误是什么。 why ms.CopyTo(allFrameStream) is not working? 为什么ms.CopyTo(allFrameStream)不起作用?

Reset Position of ms to 0 after you fill it: 填充后,将ms Position重置为0:

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

From Stream.CopyTo 来自Stream.CopyTo

Copying begins at the current position in the current stream 复制从当前流中的当前位置开始

Try executing allFrameStream.Position = 0; 尝试执行allFrameStream.Position = 0; just before writing to the PDF. 就在写入PDF之前。

After writing to ms , the position of ms is at its end. 写后ms ,位置ms是在其结束。 You have to seek to the beginning of the stream, eg with: 你必须寻找流的开头,例如:

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

After that ms.CopyTo is working correctly. 之后ms.CopyTo正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM