BitmapImage to byte[]

So Many Goblins picture So Many Goblins · Jul 6, 2011 · Viewed 57.9k times · Source

I have a BitmapImage that I'm using in a WPF application, I later want to save it to a database as a byte array (I guess it's the best way), how can I perform this conversion?

Or, alternatively, is there a better way to save a BitmapImage (or any of its base classes, BitmapSource or ImageSource) to a data repository?

Answer

Christoph Fink picture Christoph Fink · Jul 6, 2011

To convert to a byte[] you can use a MemoryStream:

byte[] data;
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmapImage));
using(MemoryStream ms = new MemoryStream())
{
    encoder.Save(ms);
    data = ms.ToArray();
}

Instead of the JpegBitmapEncoder you can use whatever BitmapEncoder you like as casperOne said.

If you are using MS SQL you could also use a image-Column as MS SQL supports that datatype, but you still would need to convert the BitmapImage somehow.