Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MemoryStream.CopyTo Not working

Tags:

c#

.net

io

c#-4.0

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. But each iteration I could see ms.Length=989548. What is the error in my code. why ms.CopyTo(allFrameStream) is not working?

like image 744
Billa Avatar asked Mar 03 '14 11:03

Billa


People also ask

What is the difference between MemoryStream and FileStream?

As the name suggests, a FileStream reads and writes to a file whereas a MemoryStream reads and writes to the memory. So it relates to where the stream is stored.

How do I write from one stream to another?

CopyTo(Stream, Int32) Reads the bytes from the current stream and writes them to another stream, using a specified buffer size. Both streams positions are advanced by the number of bytes copied.


1 Answers

Reset Position of ms to 0 after you fill it:

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

From Stream.CopyTo

Copying begins at the current position in the current stream

like image 159
dkozl Avatar answered Sep 21 '22 01:09

dkozl