views:

1193

answers:

2

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.

+3  A: 

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

Jacob G
Cannot do that either... any idea?
Tony
Can you provide some more details about your scenario? I'm having a hard time understanding why you'd need to do this.
Jacob G
@Jacob: see above for more details
Tony
@Tony: Updated with link on how to bind Image (byte[]) from Database to Image control.
Jacob G
+2  A: 

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