问题
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