c# - 从sql数据库检索图像(字节数组)并显示图像

标签 c# wpf image mvvm

在我的 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;
    }
}

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

提前致谢

最佳答案

使用下面的代码

            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;

编辑:,您可以 See the Solution here fro WPF

关于c# - 从sql数据库检索图像(字节数组)并显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26758262/

相关文章:

Android:从 Url 显示在 Webview 的图像具有高质量损失

python - matplotlib - 如何将数组保存为带有叠加文本的图像?

c# - 如何在 ICSharpCode.AvalonEdit.TextEditor 中更改文本颜色?

c# - 检查是否处理了所有枚举值

wpf - 如何防止 InvokeCommandAction 将事件传播到父元素?

wpf - 一起使用 F# 和 Caliburn.Micro

html - 在 HTML 中垂直放置图片库而不是水平放置图片库

c# - 数据库、请求、性能、缓存

c# - Auto Mapper v4.2.1 - 缺少类型映射配置或不支持的映射

c# - 注册区域与在 Prism 中添加区域有什么区别?