【问题标题】:Retrieve Image (byte array) from sql database and show the Image [duplicate]从 sql 数据库中检索图像(字节数组)并显示图像 [重复]
【发布时间】:2015-01-01 16:59:04
【问题描述】:

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

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

提前致谢

【问题讨论】:

标签: c# wpf image mvvm


【解决方案1】:

使用下面的代码

            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

【讨论】:

  • 您好,我正在检查。但它不起作用..我在 wpf 中使用图像工具。所以它需要图像源。 AspImageID.ImageUrl 是字符串
  • 在我的代码中 Uploadlogo 具有来自数据库的字节 这是我的图像源属性 private ImageSource _clientlogo;公共 ImageSource ClientLogo { 获取 { 返回 _clientlogo; } 设置 { _clientlogo = 值; OnPropertyChanged("ClientLogo"); } }
  • @Arun - 查看更新的答案链接
  • 有谁知道为什么“data:image/png;base64”在图像被存储之前被删除并在读取时重新添加?
猜你喜欢
  • 2018-07-28
  • 2021-03-25
  • 2015-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多