2017-10-20 254 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; 
    } 
} 
相关问题