C# Convert BitmapImage object to ByteArray

大兔子大兔子 提交于 2019-12-11 11:01:18

问题


How do I convert an object of BitmapImage type to a byte array?

There's plenty of examples out on the web but all of them are using methods that no longer exist for windows Store app.

best solution I've found is this, however I get an exception on the first code line when trying to run it

public static byte[] ConvertBitmapToByteArrayAsync(WriteableBitmap bitmap)
{            
    using (var stream = bitmap.PixelBuffer.AsStream())
    {                
        MemoryStream memoryStream = new MemoryStream();
        stream.CopyTo(memoryStream);
        return memoryStream.ToArray();
    }
}

exception:

A first chance exception of type 'System.AccessViolationException' occurred in System.Runtime.WindowsRuntime.dll

Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

from what I can gather it may have to do with the size of the stream but I haven't been able to figure out how to fix it.


回答1:


I hope this can help you:

  // Converting Bitmap to byte array
  private byte[] ConvertBitmapToByteArray(Bitmap imageToConvert)
  {
      MemoryStream ms = new System.IO.MemoryStream();
      imageToConvert.Save(ms, ImageFormat.Png);

      return ms.ToArray();
  }
  // Converting byte array to bitmap
  private Bitmap ConvertBytesToBitmap(byte[] BytesToConvert)
  {
      MemoryStream ms = new MemoryStream(BytesToConvert);
      try { return new Bitmap(ms); }
      catch { return null; }
  }


来源:https://stackoverflow.com/questions/21429952/c-sharp-convert-bitmapimage-object-to-bytearray

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