2014-11-05 168 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