Convert BitmapSource to MemoryStream

给你一囗甜甜゛ 提交于 2019-12-22 18:20:13

问题


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'


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/42272438/convert-bitmapsource-to-memorystream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!