简体   繁体   English

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

[英]Parameter is invalid exception when retrieving image from database to picturebox

I am retrieving the image from a SQL Server database into a PictureBox in a C# Windows application. 我正在从SQL Server数据库中将图像检索到C#Windows应用程序中的PictureBox中。 The image is a form which I don't know. 图片是我不知道的形式。

I tried this code but it throws a "parameter invalid" exception, and I also go through many answer related to this but didn't work any. 我尝试了这段代码,但是抛出了“参数无效”异常,并且我也经历了许多与此相关的答案,但是没有任何效果。

My code: 我的代码:

  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()
  {
  }

Database Image 数据库映像 在此处输入图片说明

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

Insead of using Image.FromStream, did you try using ImageConverter? 使用Image.FromStream的想法,您是否尝试过使用ImageConverter?

Sample come of using ImageConverter looks as following. 使用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);

This should resolve your issue. 这样可以解决您的问题。

Thanks and regards, Chetan Ranpariya 谢谢和问候,Chetan Ranpariya

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM