首先定義數據庫連接字符串:
String strCn = "server=.;database=DB_NAME;user=sa;pwd=XXX";
讀取圖片,將圖片轉換二進制保存到數據庫方法:
SqlConnection cn = new SqlConnection(strCn); SqlCommand cmd = new SqlCommand("INSERT INTO ProductID_Image (ProductID,ImageData) VALUES ('1',@BLOBData)", cn); String strBLOBFilePath = @"C:/Users/Administrator/Desktop/打印模板.jpeg"; FileStream fsBLOBFile = new FileStream(strBLOBFilePath, FileMode.Open, FileAccess.Read); Byte[] bytBLOBData = new Byte[fsBLOBFile.Length]; fsBLOBFile.Read(bytBLOBData, 0, bytBLOBData.Length); fsBLOBFile.Close(); SqlParameter prm = new SqlParameter("@BLOBData", SqlDbType.VarBinary, bytBLOBData.Length, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, bytBLOBData); cmd.Parameters.Add(prm); cn.Open(); cmd.ExecuteNonQuery(); cn.Close();
讀取數據庫中二進制數據,轉換成圖片方法:
SqlConnection cn = new SqlConnection(strCn); cn.Open(); SqlCommand cmd = new SqlCommand("select ProductID,ImageData from ProductID_Image", cn); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds, "ProductID_Image"); int c = ds.Tables["ProductID_Image"].Rows.Count; if (c > 0) { Byte[] byteBLOBData = new Byte[0]; byteBLOBData = (Byte[])(ds.Tables["ProductID_Image"].Rows[c - 1]["ImageData"]); MemoryStream stmBLOBData = new MemoryStream(byteBLOBData); pictureBox1.Image = Image.FromStream(stmBLOBData); } cn.Close();