Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'

like image 455
Aarti Dhiman Avatar asked Feb 16 '17 11:02

Aarti Dhiman


1 Answers

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;
}
like image 131
BWA Avatar answered Oct 19 '22 20:10

BWA