2017-10-20 126 views
0

我是WPF編程和Microsoft SQL服務器的新手。我想插入圖像並從數據庫中檢索圖像。我瞭解到如何將圖像(Windows.Controls.Image)轉換爲byte[]並將其存儲到數據庫,但我無法將其從byte[]轉換回Image以將其顯示在WPF窗口中。如何從C#插入圖像並從數據庫中檢索圖像?

private Image byteArrayToImage(byte[] arr) 
{ 
    MemoryStream stream = new MemoryStream(); 
    stream.Write(arr, 0, arr.Length); 
    stream.Position = 0; 
    System.Drawing.Image img = System.Drawing.Image.FromStream(stream); // Exception 
    BitmapImage returnImage = new BitmapImage(); 
    returnImage.BeginInit(); 
    MemoryStream ms = new MemoryStream(); 
    img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp); 
    ms.Seek(0, SeekOrigin.Begin); 
    returnImage.StreamSource = ms; 
    returnImage.EndInit(); 
    Image ans = new Image(); 
    ans.Source = returnImage; 
    return ans; 
} 

輸出:

System.ArgumentException: '參數無效'

private byte[] imageToArray(System.Drawing.Image img) // Work well 
{ 
    MemoryStream ms = new MemoryStream(); 
    FileInfo fi = new FileInfo(tempData); // File name 
    img.Save(ms, System.Drawing.Imaging.ImageFormat.Png); 
    byte[] pic = ms.ToArray(); 
    return pic; 
} 
+0

我編輯了你的問題標題。請不要在問題標題中加強標籤。閱讀[這裏](https://stackoverflow.com/help/tagging)爲什麼。 – dymanoid

+0

你試過這個嗎? https://stackoverflow.com/questions/9564174/convert-byte-array-to-image-in-wpf – mm8

+0

或[this](https://stackoverflow.com/a/39366641/2029607) – XAMlMAX

回答

-2

System.Drawing.Image.FromStream告訴你什麼時候該發生異常。

流沒有有效的圖像格式 - 或 - 流爲空。

有時,API文檔有助於:o)檢查null並檢查發佈/檢索的文件格式。

由於downvote的詳細說明: 圖像格式是字節不兼容的 - 如果將.bmp放入字節數組並將其存儲到數據庫中並稍後檢索它,則還必須檢索bmp。 Png不會工作 - 它存儲完全不同。

+0

不是downvoter,而是因爲System.Drawing被討厭的'WinForms'和不光榮的'WPF'使用。 – XAMlMAX

+0

告訴這個線程 - 他使用了它,詢問了什麼是錯誤的,並且我指出了他告訴錯誤的API。 –

+0

實際上OP引用了'Windows.Controls.Image'。 – XAMlMAX

-1

首先,爲您的PictureHelper創建一個靜態類。您必須導入在WPF使用BitmapImage的,我認爲它的using System.Drawing.Imaging;

using System; 
using System.Drawing; 
using System.Drawing.Drawing2D; 
using System.Drawing.Imaging; 
using System.IO; 
using System.Windows; 
using System.Windows.Forms; 
using System.Windows.Threading; 
using Application = System.Windows.Forms.Application; 
using Size = System.Drawing.Size; 

public static class PictureHelper 
{ 
    public static BitmapImage GetImage(object obj) 
    { 
     try 
     { 
      if (obj == null || string.IsNullOrEmpty(obj.ToString())) return new BitmapImage(); 

      #region Picture 

      byte[] data = (byte[])obj; 

      MemoryStream strm = new MemoryStream(); 

      strm.Write(data, 0, data.Length); 

      strm.Position = 0; 

      Image img = Image.FromStream(strm); 

      BitmapImage bi = new BitmapImage(); 

      bi.BeginInit(); 

      MemoryStream ms = new MemoryStream(); 

      img.Save(ms, ImageFormat.Bmp); 

      ms.Seek(0, SeekOrigin.Begin); 

      bi.StreamSource = ms; 

      bi.EndInit(); 

      return bi; 

      #endregion 
     } 
     catch 
     { 
      return new BitmapImage(); 
     } 
    } 

    public static string PathReturner(ref string name) 
     { 
      string filepath = ""; 
      OpenFileDialog openFileDialog = new OpenFileDialog(); 

      openFileDialog.Multiselect = false; 
      openFileDialog.Filter = @"Image Files(*.jpeg;*.bmp;*.png;*.jpg)|*.jpeg;*.bmp;*.gif;*.png;*.jpg"; 
      openFileDialog.RestoreDirectory = true; 
      openFileDialog.Title = @"Please select an image file to upload."; 

      MiniWindow miniWindow = new MiniWindow(); 
      miniWindow.Show(); 

      if (openFileDialog.ShowDialog() == DialogResult.OK) 
      { 
       filepath = openFileDialog.FileName; 
       name = openFileDialog.SafeFileName; 
      } 

      miniWindow.Close(); 
      miniWindow.Dispose(); 
      return filepath; 
     } 

     public static string Encryptor(this string safeName) 
     { 
      string extension = Path.GetExtension(safeName); 

      string newFileName = String.Format(@"{0}{1}{2}", Guid.NewGuid(), DateTime.Now.ToString("MMddyyyy(HHmmssfff)"), extension); 
      newFileName = newFileName.Replace("(", "").Replace(")", ""); 
      return newFileName; 
     } 


     public static Bitmap ByteToBitmap(this byte[] blob) 
     { 
      MemoryStream mStream = new MemoryStream(); 
      byte[] pData = blob; 
      mStream.Write(pData, 0, Convert.ToInt32(pData.Length)); 
      Bitmap bm = new Bitmap(mStream, false); 
      mStream.Dispose(); 
      return bm; 

     } 

     public static byte[] BitmapToByte(this Image img) 
     { 
      byte[] byteArray = new byte[0]; 
      using (MemoryStream stream = new MemoryStream()) 
      { 
       img.Save(stream, ImageFormat.Png); 
       stream.Close(); 

       byteArray = stream.ToArray(); 
      } 
      return byteArray; 
     } 
} 

這是與畫面

public SortableBindingList<Candidate> RetrieveManyWithPicture(Candidate entity) 
{ 
    var command = new SqlCommand { CommandText = "RetrievePictureCandidates", CommandType = CommandType.StoredProcedure }; 

    command.Parameters.AddWithValue("@CandidateId", entity.CandidateId).Direction = ParameterDirection.Input; 


    DataTable dt = SqlHelper.GetData(command); //this is where I retrieve the row from db, you have your own code for retrieving, so make sure it works. 

    var items = new SortableBindingList<Candidate>(); 

    if (dt.Rows.Count <= 0) return items; 
    foreach (DataRow row in dt.Rows) 
    { 
     Candidate item = new Candidate(); 

     item.CandidateId = row["CandidateId"].GetInt(); 
     item.LastName = row["LastName"].GetString(); 
     item.FirstName = row["FirstName"].GetString(); 

     item.PictureId = row["PictureId"].GetInt(); 
     item.PhotoType = PictureHelper.GetImage(row["Photo"]); //in my db, this is varbinary. in c#, this is byte[] 

     items.Add(item); 

    } 

    return items; 
} 

檢索類(在我的情況下,候選)這是上傳圖片從WPF到DB,我在我的按鈕用於

private void UploadButton_Click(object sender, EventArgs e) 
{ 
    string safeName = ""; 
    string pathName = PictureHelper.PathReturner(ref safeName); 
    PictureViewModel vm = new PictureViewModel(); 
    if (pathName != "") 
    { 
     safeName = safeName.Encryptor(); 

     FileStream fs = new FileStream(pathName, FileMode.Open, FileAccess.Read); 
     byte[] data = new byte[fs.Length]; 


     fs.Read(data, 0, Convert.ToInt32(fs.Length)); 
     fs.Close(); 

     PicNameLabel.Text = safeName; 
     vm.Entity.Name = safeName; //this is the byte[] 

     Bitmap toBeConverted = PictureHelper.ByteToBitmap(data); //convert the picture before sending to the db 

     vm.Entity.Photo = PictureHelper.BitmapToByte(toBeConverted); 
     vm.Entity.Path = pathName; 

     CandidatePictureBox.Image = toBeConverted; 

     vm.Insert(vm.Entity); 

    } 
} 

這是保存圖片的方法

public bool Insert(Picture entity) 
{ 
    var command = new SqlCommand(); 

    try 
    { 
     command.CommandText = "AddPicture"; 
     command.CommandType = CommandType.StoredProcedure; 

     command.Parameters.AddWithValue("@Name", entity.Name).Direction = ParameterDirection.Input; 
     command.Parameters.AddWithValue("@Photo", entity.Photo).Direction = ParameterDirection.Input; 

     int result = SqlHelper.ExecuteNonQuery(command); //executenonquery will save the params to the db 

     return true; 
    } 
    catch (Exception) 
    { 
     return false; 
    } 
} 
相關問題