Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert System.Drawing.Image to System.Windows.Controls.Image?

Is there a way in C# to do this conversion and back?

I have a WPF app which has a Image control. I'm trying to save the image in that control to a SQL Database.

In my Entity Model, the datatype of the picture column in my database is a byte[]. So I found a method to convert a System.Drawing.Image to a byte[] and back. But I haven't found a method to convert from System.Windows.Controls.Image to a byte[].

So that's why I now need to do the above conversion.

like image 709
Tony The Lion Avatar asked Mar 09 '10 16:03

Tony The Lion


2 Answers

If you have a byte array that represents a file that WPF can decode (bmp, jpg, gif, png, tif, ico), you can do the following:

BitmapSource LoadImage(Byte[] imageData)
{
    using (MemoryStream ms = new MemoryStream(imageData))
    {
        var decoder = BitmapDecoder.Create(ms,
            BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
        return decoder.Frames[0];
    }
}

Likewise, to convert it back, you can do the following:

byte[] SaveImage(BitmapSource bitmap)
{
    using (MemoryStream ms = new MemoryStream())
    {
        var encoder = new BmpBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create(bitmap));
        encoder.Save(ms);

        return ms.GetBuffer();
    }
}
like image 147
Abe Heidebrecht Avatar answered Sep 16 '22 12:09

Abe Heidebrecht


Well, one is an image and one is a control that shows an image, so I don't think that there's a conversion between the two. But, you could set the Source of the ...Controls.Image to be your ...Drawing.Image.

Edit based on update

Does this do what you need - http://msdn.microsoft.com/en-us/library/ms233764%28VS.100%29.aspx

like image 26
Jacob G Avatar answered Sep 19 '22 12:09

Jacob G