Aarti Dhiman
Aarti Dhiman

Reputation: 75

Convert BitmapSource to MemoryStream

How Do I convert BitmapSource to MemoryStream. Though I tried some code:

private Stream StreamFromBitmapSource(BitmapSource writeBmp)
{
    Stream bmp;
    using (bmp = new MemoryStream())
    {                    
        BitmapEncoder enc = new BmpBitmapEncoder();
        enc.Frames.Add(BitmapFrame.Create(writeBmp));
        enc.Save(bmp);                                     
    }

   return bmp;
}

It doesn't give any error but after putting debugging point it is showing some exceptions which are listed below.

Capacity: 'printStream.Capacity' threw an exception of type 'System.ObjectDisposedException' Length: 'printStream.Length' threw an exception of type 'System.ObjectDisposedException' Position: 'printStream.Position' threw an exception of type 'System.ObjectDisposedException'

Upvotes: 5

Views: 5977

Answers (2)

BWA
BWA

Reputation: 5764

using (bmp = new MemoryStream()) causes bmp object is destroyed on end using block. And You return bmp variable which is destroyed.

Remove using:

private Stream StreamFromBitmapSource(BitmapSource writeBmp)
{
    Stream bmp = new MemoryStream();

    BitmapEncoder enc = new BmpBitmapEncoder();
    enc.Frames.Add(BitmapFrame.Create(writeBmp));
    enc.Save(bmp);                                             

   return bmp;
}

Upvotes: 8

moondaisy
moondaisy

Reputation: 4491

The problem here is that you are creating bmp inside an using, that's why it has been disposed before you return it (it is disposed once you leave the using) and that explains the exceptions you receive.

private Stream StreamFromBitmapSource(BitmapSource writeBmp)
{
    Stream bmp= new MemoryStream();
    using (enc = new BmpBitmapEncoder())
    {                    
        enc.Frames.Add(BitmapFrame.Create(writeBmp));
        enc.Save(bmp);                                     
    }

   return bmp;
}

Upvotes: 0

Related Questions