C# 将 BitmapImage 对象转换为 ByteArray

问题描述:

如何将 BitmapImage 类型的对象转换为字节数组?

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

网络上有很多示例,但所有示例都使用了 Windows Store 应用程序不再存在的方法.

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

例外:

System.AccessViolationException"类型的第一次机会异常发生在 System.Runtime.WindowsRuntime.dll

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.

希望能帮到你:

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