开发者

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

开发者 https://www.devze.com 2022-12-22 21:19 出处:网络
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.

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.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消