使用Visual C#将图像添加到SQL数据库

我正在开发一个用于图像处理的可视化C#程序。我正在尝试使用Visual C#(Windows窗体)和ADO.NET将图像添加到sql数据库。

我已经使用filestream方法将图像转换为二进制forms,但图像字节未保存在数据库中。 在数据库图像列中,它显示并且没有数据被保存!

我已经尝试了很多插入方法(有和没有存储过程..等)但总是在数据库中得到相同的东西。

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

我没有在代码中收到错误。 图像已转换,输入在数据库中完成,但在sql数据库中显示。

应将选定的文件流转换为字节数组。

  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 

现在这很好用。 数据库仍显示<二进制数据>但可以使用memorystream方法将其转换回图像。

谢谢大家…

试试这样的事情:

 byte[] fileBytes=System.IO.File.ReadAllBytes("path to file"); System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand("insert into table(blob,filename) values (@blob,@name)"); command.Parameters.AddWithValue("blob", fileBytes); command.Parameters.AddWithValue("name", "filename"); command.ExecuteNonQuery(); 

假设您使用VARBINARY存储图像( 您应该使用它 ),您可能需要使SqlParameter更强类型化:

而不是

 cmd.Parameters.Add(new SqlParameter("@Imgg", image)); 

你会用:

 cmd.Parameters.Add("@Imgg", SqlDbType.VarBinary).Value = (SqlBinary)image; 

您还可以使用System.IO.File.ReadAllBytes来缩短代码,将文件路径转换为字节数组。

执行此存储过程:

 create procedure prcInsert ( @txtEmpNo varchar(6), @photo image ) as begin insert into Emp values(@txtEmpNo, @photo) end 

表Emp:

 create table Emp ( [txtEmpNo] [varchar](6) NOT NULL, imPhoto image )