Windowform 窗体关联数据库存储,读取图片,参考代码

namespace flowlayoutpanel_容器
{
    public partial class picturebox : Form
    {
        public picturebox()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //从硬盘上读取图片显示在界面
            openFileDialog1.Filter = "@.Jpg|*.jpg|@.Png|*.png|@.Jif|*.jif|All files|*.*";
            DialogResult dr = openFileDialog1.ShowDialog();
            if (dr == DialogResult.OK)
            {
                //将图片读入流中
                FileStream fs = new FileStream(openFileDialog1.FileName,FileMode.Open,FileAccess.Read);
                Image img = System.Drawing.Bitmap.FromStream(fs); //绘制
                pictureBox1.Image = img;   //指定
                fs.Close();

            }
        }
        //将图片存入到数据库
        private void button2_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "@.Jpg|*.jpg|@.Png|*.png|@.Jif|*.jif|All files|*.*";  //存储格式
            DialogResult dr = openFileDialog1.ShowDialog();
            if (dr==DialogResult.OK)
            {
               FileStream fs = new FileStream(openFileDialog1.FileName,FileMode.Open,FileAccess.Read );
               BinaryReader br = new BinaryReader(fs);  //二进制读取器
              byte[] fuffer= br.ReadBytes(int.Parse (fs.Length.ToString ()));

                //连接数据库
              SqlConnection coon = new SqlConnection("server=.;database=master;user=sa;pwd=123");
              SqlCommand cmd = coon.CreateCommand();
              coon.Open();
              cmd.CommandText = "insert into imagetable values (@fuffer)";
              cmd.Parameters.Clear();
              cmd.Parameters.Add("@fuffer",fuffer );
              cmd.ExecuteNonQuery();
              cmd.Dispose();
              coon.Close();
            }
        }
        //从数据库读取图片
        private void button3_Click(object sender, EventArgs e)
        {
            SqlConnection coon = new SqlConnection("server=.;database=master;user=sa;pwd=123");
            SqlCommand cmd = coon.CreateCommand();
            coon.Open();
            cmd.CommandText = "select *from imagetable where code=7";
            SqlDataReader dr = cmd.ExecuteReader();
            byte[] buffer=null;
            if (dr.Read())
            {
                  buffer=(byte[])dr["imags"];
            }
            
            coon.Close();

            //将二进制buffer显示为图片
            MemoryStream ms = new MemoryStream(buffer);
            Image img = System.Drawing.Bitmap.FromStream(ms);
            pictureBox1.Image = img;

            
        }
    }
}

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。