Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

asp.net - Adding an image to SQL database using Visual C#

I am working on a visual C# program for image processing.I am trying to add image to sql database using Visual C# (Windows forms) and ADO.NET.

I have converted the image to binary form with filestream method but the image bytes are not getting saved in database. At the database image column, it says < Binary data > and no data is getting saved!

I have tried many methods for inserting( with and without stored procedures..etc) but always getting the same thing at database.

private void button6_Click(object sender, EventArgs e)
{
   try
   {
      byte[] image = null;
      pictureBox2.ImageLocation = textBox1.Text;
      string filepath = textBox1.Text;
      FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read);
      BinaryReader br = new BinaryReader(fs);
      image = br.ReadBytes((int)fs.Length);
      string sql = " INSERT INTO ImageTable(Image) VALUES(@Imgg)";
      if (con.State != ConnectionState.Open)
         con.Open();
      SqlCommand cmd = new SqlCommand(sql, con);
      cmd.Parameters.Add(new SqlParameter("@Imgg", image));
      int x= cmd.ExecuteNonQuery();
      con.Close();
      MessageBox.Show(x.ToString() + "Image saved");
   }
}

I am not getting error in code. the image got converted and entry is done in database but says < Binary Data > at the sql database.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The selected file stream should be converted to byte array.

        FileStream FS = new FileStream(filepath, FileMode.Open, FileAccess.Read); //create a file stream object associate to user selected file 
        byte[] img = new byte[FS.Length]; //create a byte array with size of user select file stream length
        FS.Read(img, 0, Convert.ToInt32(FS.Length));//read user selected file stream in to byte array

Now this works fine. Database still shows < Binary data > but it could be converted back to image using memorystream method.

Thanks to all...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...