码迷,mamicode.com
首页 > 数据库 > 详细

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

时间:2015-06-08 17:09:07      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:

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;

            
        }
    }
}

 

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

标签:

原文地址:http://www.cnblogs.com/275147378abc/p/4561196.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!