从数据库到图片框检索图像时参数无效异常

时间:2017-01-07 04:36:05

标签: c# sql-server image winforms

我正在从SQL Server数据库中将图像检索到C#Windows应用程序中的PictureBox。图像是我不知道的形式。

我尝试了这段代码,但它抛出了一个“参数无效”异常,我也经历了很多与此相关的答案,但没有任何效果。

我的代码:

  SqlConnection sql_con  = new SqlConnection();
  sql_con.ConnectionString = @"Server=abc-14;Database=Abcstudent;User Id=sa; Password=abc;";

  if (sql_con.State == ConnectionState.Closed) 
      sql_con.Open();

  try
  {
      string query = "Select grno, PICStudent from GENREG where grno = 1";                        
      SqlCommand sql_cmd = new SqlCommand(query, sql_con);

      sql_cmd.ExecuteNonQuery();

      SqlDataAdapter sql_adp = new SqlDataAdapter(sql_cmd);               
      sql_adp.Fill(sql_ds);    
  }
  catch(Exception ex)
  {
  }

  // code for retrieving image to picture box 
  try
  {
       DataRow myRow;
       byte[] MyData = new byte[0];
       myRow = sql_ds.Tables[0].Rows[0];

       MyData = (byte[])myRow["PICStudent"];
       MemoryStream stream = new MemoryStream(MyData);
       pictureBox1.Image = Image.FromStream(stream);  // getting error here
  }
  catch()
  {
  }

数据库图片 enter image description here

2 个答案:

答案 0 :(得分:1)

 SqlConnection con = new SqlConnection("Data Source=SERVERNAME;Initial Catalog=DATABASENAME;Integrated Security=SSPI;");
        con.Open();
        SqlCommand cmd = new SqlCommand("select picbox from picture1 where id=1", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        if (ds.Tables[0].Rows.Count > 0)
        {
            MemoryStream ms = new MemoryStream((byte[])ds.Tables[0].Rows[0]["picbox"]);
            pictureBox1.Image = new Bitmap(ms);
        }

答案 1 :(得分:1)

使用Image.FromStream的Insead,您是否尝试使用ImageConverter?

使用ImageConverter的示例如下所示。

byte[] filedata = (byte[])myRow["PICStudent"];
ImageConverter imageConverter = new System.Drawing.ImageConverter();
System.Drawing.Image image = imageConverter.ConvertFrom(fileData) as System.Drawing.Image;
image.Save(imageFullPath, System.Drawing.Imaging.ImageFormat.Jpeg);

这可以解决您的问题。

谢谢和问候, Chetan Ranpariya