wpf 从 sql 数据库中检索图像(字节数组)并显示图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26758262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 12:40:45  来源:igfitidea点击:

Retrieve Image (byte array) from sql database and show the Image

c#wpfimagemvvm

提问by Arun

In my wpf mvvm application I write a code for image upload and save to database. The code is working fine and the image save to the data base. Here I need to retrieve the image from the database and show in a Image box.Here is my Insert code

在我的 wpf mvvm 应用程序中,我编写了一个用于图像上传并保存到数据库的代码。代码运行良好,图像保存到数据库中。这里我需要从数据库中检索图像并显示在图像框中。这是我的插入代码

public void Upload(object obj)
{
    try
    {
        Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
        dlg.DefaultExt = ".png";
        dlg.Filter = "Image files (*.png;*.jpg)|*.png;*.jpg";
        Nullable<bool> result = dlg.ShowDialog();
        if (result == true)
        {
            string filename = dlg.FileName;
            UploadText = filename;
            FileStream FS = new FileStream(filename, FileMode.Open, FileAccess.Read);
            byte[] img = new byte[FS.Length];
            FS.Read(img, 0, Convert.ToInt32(FS.Length));
            UploadLogo = img;
            Stream reader = File.OpenRead(filename);
            System.Drawing.Image photo = System.Drawing.Image.FromStream((Stream)reader);
            MemoryStream finalStream = new MemoryStream();
            photo.Save(finalStream, ImageFormat.Png);
            // translate to image source
            PngBitmapDecoder decoder = new PngBitmapDecoder(finalStream, BitmapCreateOptions.PreservePixelFormat,
                                                BitmapCacheOption.Default);
            ClientLogo = decoder.Frames[0]; ;
        }
    }

    catch (Exception ex)
    {
        throw ex;
    }
}

how can I convert this byte data to image

如何将此字节数据转换为图像

Thanks in advance

提前致谢

回答by prog1011

Use Below Code

使用下面的代码

            object binaryData = ("select ImageDataColunm from table where id=yourID");// use your code to retrive image from database and store it into 'object' data type
            byte[] bytes = (byte[])binaryData;
            string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
            AspImageID.ImageUrl= "data:image/png;base64," + base64String;

EDIT:and you can See the Solution here fro WPF

编辑:您可以在此处查看 WPF 的解决方案