读取数据库图片字段方法:
  protected void LoadPicture()
        {
            Image img = null;

            if (this.gl_studentid.Length==0)
            {
                img = Image.FromFile("NoPicture.png");//如果数据库中没有图片则加载NoPicture.png这张图片
                this.pictureBox1.Image = img;
                return;
            }

            string sql = "select * from student where studentid='" + gl_studentid + "'";

            DataTable dt = DBUtil.GetData(sql);

            if (dt.Rows.Count>0)
            {
                try  //用try 做判断 ,因为转化过程可能出错
                {
                    byte[] bytes = (byte[])dt.Rows[0]["img"];

                    MemoryStream ms = new MemoryStream(bytes);  //核心方法  将图片加载到内存流中

                    this.pictureBox1.Image = Image.FromStream(ms);

                }
                catch (Exception)
                {
                    img = Image.FromFile("NoPicture.png");

                    this.pictureBox1.Image=img;
                }
            }               
        }
向数据库中上传图片文件方法:(这里方便采用修改数据库的图片文件,原理相同)
       private void btnSubmit_Click(object sender, EventArgs e)
        {
            string filePath = this.txtFilePath.Text.ToString();

            if (filePath.Length==0)
            {
                MessageBox.Show("请选择图片!");
                return;
            }
            if (gl_studentid.Length==0)
            {
                MessageBox.Show("请选择要修改的记录!");
            }

            string sql = "update student set img=@img where studentid=@studentid";

            SqlParameter p1 = new SqlParameter("@img", SqlDbType.Image);
            
            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            byte[] bytes = new byte[fs.Length];
            fs.Seek(0, SeekOrigin.Begin);  //定义开始读文件的位置,为0位置  SeekOrigin.Begin意为设置0为一个开始标志位
            fs.Read(bytes, 0, (int)fs.Length);
            p1.Value = bytes;
           
            SqlParameter p2 = new SqlParameter("@studentid", gl_studentid);

            using (SqlConnection conn=new SqlConnection(sqlconn))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.CommandText = sql;
                cmd.Parameters.Add(p1);
                cmd.Parameters.Add(p2);

                cmd.ExecuteNonQuery();

                fs.Close();
                fs.Dispose();

                MessageBox.Show("图片修改成功!");

                this.LoadPicture();

            }
        }


本文转载:CSDN博客