2014-11-05 165 views
1

在我的wpf mvvm应用程序中,我编写了一个图像上传代码并保存到数据库。 代码工作正常,图像保存到数据库。 在这里,我需要从数据库中检索图像,并显示在图像box.Here是我的插入代码从sql数据库检索图像(字节数组)并显示图像

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

我怎么能事先此字节的数据转换为图像

感谢

+0

这回答了几个星期前http://stackoverflow.com/questions/25862980/how-to-download-and-view-images-from-sql-server-table/25863338 – Aymeric 2014-11-05 13:22:30

回答

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

+0

你好,我我正在检查。但它不工作.. 我在wpf.so中使用图像工具它需要图像源。 AspImageID.ImageUrl是我的代码中的字符串 – Arun 2014-11-05 13:35:23

+0

Uploadlogo具有来自数据库的字节 这是我的图像资源属性 private ImageSource _clientlogo; public ImageSource ClientLogo { get { return _clientlogo; } set { _clientlogo = value; OnPropertyChanged(“ClientLogo”); } } – Arun 2014-11-05 13:36:37

+0

@Arun - 查看更新后的答案链接 – prog1011 2014-11-05 13:44:49