System.IO.MemoryStream stream = new System.IO.MemoryStream(); System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bFormat = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); bFormat.Serialize(stream,img); byte[] by = new byte[stream.Length]; stream.Read(by,0,by.Length); System.Data.SqlClient.SqlConnection cnn = new System.Data.SqlClient.SqlConnection("连接字符串"); System.Data.SqlClient.SqlCommand cm = new System.Data.SqlClient.SqlCommand(); cm.Connection = cnn; cm.CommandText = "insert into table1 (field1,field2) values(@field1,@field2)";
PictureBox.Image.Save(impStream,System.Drawing.Imaging.ImageFormat.Jpeg);// 声明数据库的新增行
// 比如DataRow newRow,字段为Img
newRow["Img"] = impStream;将新行加入到数据表中并更新就可以了;
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "BMP 文件(*.bmp)|*.bmp|JPG 文件(*.jpg)|*.jpg|GIF 文件(*.gif)|*.gif|TIFF 文件(*.tiff)|*.tiff|WMF 文件(*.wmf)|*.wmf";
openFileDialog1.FilterIndex = 1;
openFileDialog1.Title = "打开图象文件";
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog( ) == DialogResult.OK)
{
string strFileName = openFileDialog1.FileName;
Bitmap m_bitmap = new Bitmap(strFileName);
this.pictureBox1.Image = m_bitmap;
}
}
//picturebox1图片保存到DataSet1
private void SavePicToDataSet(CurrencyManager thispic)
{
//if(this.pictureBox1.Image.!= null)
MemoryStream ms = new MemoryStream ();
this.pictureBox1.Image.Save (ms, System.Drawing.Imaging.ImageFormat.Bmp);
byte [] myData = new Byte [ms.Length ];
ms.Position = 0;
ms.Read (myData,0,Convert.ToInt32 (ms.Length ));
DataRow drv = ((DataRowView)thispic.Current).Row;
drv["pic"] = myData;
System.IO.MemoryStream stream = new System.IO.MemoryStream();
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bFormat = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
bFormat.Serialize(stream,img);
byte[] by = new byte[stream.Length]; stream.Read(by,0,by.Length);
System.Data.SqlClient.SqlConnection cnn = new System.Data.SqlClient.SqlConnection("连接字符串");
System.Data.SqlClient.SqlCommand cm = new System.Data.SqlClient.SqlCommand();
cm.Connection = cnn;
cm.CommandText = "insert into table1 (field1,field2) values(@field1,@field2)";
cm.Parameters.Add("@field1",SqlDbType.VarChar);
cm.Parameters["@field1"].Value = "test";
cm.Parameters.Add("@field2",SqlDbType.Image );
cm.Parameters["@field2"].Value = by;
cnn.Open();
cm.ExecuteNonQuery();
cnn.Close();