Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BitmapImage to byte[]

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?

like image 586
So Many Goblins Avatar asked Jul 06 '11 14:07

So Many Goblins


2 Answers

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.

like image 200
Christoph Fink Avatar answered Oct 16 '22 15:10

Christoph Fink


You will have to use an instance of a class that derives from BitmapEncoder (such as BmpBitmapEncoder) and call the Save method to save the BitmapSource to a Stream.

You would choose the specific encoder depending on the format you want to save the image in.

like image 39
casperOne Avatar answered Oct 16 '22 15:10

casperOne