1.选择图片
#region 选择图片 private void btPic_Click(object sender, EventArgs e) { try { string pathName; if (this.openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) { pathName = this.openFileDialog1.FileName; System.Drawing.Image img = System.Drawing.Image.FromFile(pathName); this.pboxPic.Image = img; this.txtPic.Text = pathName; //将图像读入到字节数组 System.IO.FileStream fs = new System.IO.FileStream(pathName, System.IO.FileMode.Open, System.IO.FileAccess.Read); byte[] buffByte = new byte[fs.Length]; fs.Read(buffByte, 0, (int)fs.Length); fs.Close(); } } catch (Exception ex) { Msg.InfoBox(ex.Message); } } #endregion
2.保存到数据库
private static string txtPath = AppDomain.CurrentDomain.BaseDirectory + "111.txt"; private static SqlConnection sqlConn = new SqlConnection(GetConn()); //建立Command命令 string sql = @"Insert into tabel(id,pic,Note,create_time)" + "values(@id,@pic,@Note,@create_time)"; //获取最大值 mModel.AutoID = 123; SqlCommand sqlCommand1 = new SqlCommand(); sqlCommand1.CommandType = System.Data.CommandType.Text; sqlCommand1.CommandText = sql; sqlCommand1.Connection = sqlConn; //创建Parameter sqlCommand1.Parameters.Add("@id", System.Data.SqlDbType.Int); sqlCommand1.Parameters[0].Value = mModel.AutoID; sqlCommand1.Parameters.Add("@pic", System.Data.SqlDbType.Image); sqlCommand1.Parameters[1].Value = buffByte; sqlCommand1.Parameters.Add("@Note", System.Data.SqlDbType.VarChar); sqlCommand1.Parameters[2].Value = mModel.Note; sqlCommand1.Parameters.Add("@create_time", System.Data.SqlDbType.DateTime); sqlCommand1.Parameters[3].Value = mModel.CreateTime; try { if (sqlConn.State == ConnectionState.Closed) { sqlConn.Open(); } sqlCommand1.ExecuteNonQuery(); isDone = true; return "信息添加成功!"; } catch (Exception ex) { return ex.Message; } finally { sqlCommand1.Clone(); sqlConn.Close(); }
3.查询图片信息
public byte[] GetImage(int _AutoID) { if (sqlConn.State == ConnectionState.Closed) { sqlConn.Open(); } SqlCommand cmd = new SqlCommand(string.Format("SELECT pic FROM bn_CraftPic WHERE id={0}", _AutoID), sqlConn); SqlDataReader reader = cmd.ExecuteReader(); reader.Read(); byte[] buf = (byte[])reader[0]; reader.Close(); sqlConn.Close(); return buf; }
4.显示图片
MemoryStream buf = new MemoryStream((Byte[])dtMaster.Rows[CurrenMager.Position]["Pic"]); Image image = Image.FromStream(buf, true); pboxPic.Image = image;
浙公网安备 33010602011771号