C#将图片以二进制流形式存到数据库,并读取显示

时间:2021-11-30 21:44:06
        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "图片文件|*.png;*.jpg";
           if(DialogResult.OK== ofd.ShowDialog())
           {
               imagecatalog = ofd.FileName;
               textBoxImageCatalog.Text = imagecatalog;
           }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            FileStream fs =new FileStream(imagecatalog,FileMode.Open,FileAccess.Read);
            byte[] bytes =new byte[fs.Length];

            fs.Read(bytes,0,(int)fs.Length);

            string sql = "insert into pic values(" + textBoxImageID.Text + ",@image)";
            SqlParameter[] parameter = { new SqlParameter("@image", bytes) };

            int rows = DBUtil.BinaryDate(sql, parameter);
            MessageBox.Show(rows.ToString());

        }

        private void button3_Click(object sender, EventArgs e)
        {
            string sql = "select * from pic where id = " + textBoxID.Text;
            DataTable dt = DBUtil.GetData(sql);

            if(dt.Rows.Count>0)
            {
                byte[] bytes =(byte[])dt.Rows[0]["image"];

                MemoryStream ms = new MemoryStream(bytes);

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