转换为System.Drawing.Image到System.Windows.Controls.Image? [英] Convert System.Drawing.Image to System.Windows.Controls.Image?

查看:654
本文介绍了转换为System.Drawing.Image到System.Windows.Controls.Image?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有在C#的方式来做到这一点的转换和回?



我有有一个Image控件一个WPF应用程序。我想保存在控制到SQL数据库的形象。



在我的实体模型,在我的数据库中的图像列的数据类型是字节[] 。所以我找到一个方法来一个System.Drawing.Image对象转换为字节[] 和背部。但是,我还没有发现从System.Windows.Controls.Image转换为字节[]



<方法p>所以这就是为什么我现在需要做上述转换。


解决方案

如果你有一个字节数组,表示一个文件WPF可以解码(BMP,JPG,GIF,PNG,TIF,ICO),你可以做到以下几点:

 的BitmapSource的LoadImage(字节]使用的imageData)
{
(MemoryStream的毫秒=新的MemoryStream(为imageData))
{
VAR解码器= BitmapDecoder.Create(MS,
BitmapCreateOptions.PreservePixelFormat ,BitmapCacheOption.OnLoad);
返回decoder.Frames [0];
}
}



同样地,将其转换回,你可以做以下内容:

 字节[] SaveImage(的BitmapSource位图)
{$使用(MemoryStream的MS b $ b =新的MemoryStream ())
{
变种编码器=新BmpBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(位图));
encoder.Save(毫秒);

返回ms.GetBuffer();
}
}


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

这篇关于转换为System.Drawing.Image到System.Windows.Controls.Image?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆