zoukankan      html  css  js  c++  java
  • 利用OpenFileDialog 获取图片存储到数据库中

    private void button1_Click(object sender, EventArgs e)
            {
                string fName;
                OpenFileDialog openFileDialog = new OpenFileDialog();//实例化
                openFileDialog.InitialDirectory = "e:\141\";//打开的默认路径
                openFileDialog.Filter = "图像文件 (*.BMP;*.JPG;*.GIF;*.PNG)|*.BMP;*.JPG;*.GIF;*.PNG"; 
                openFileDialog.RestoreDirectory = true;
                openFileDialog.FilterIndex = 1;
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    fName = openFileDialog.FileName;
                    //textBox1.Text = File.ReadAllText(fName);
                    FileStream fs=new FileStream (fName ,FileMode.Open );
                    byte [] imgbt=new byte [fs .Length ];
                    BinaryReader br = new BinaryReader(fs);
                    imgbt = br.ReadBytes(Convert.ToInt32(fs.Length));
                    string cnnstr = "server=.;User ID=sa;Password=admin;Database=student";

                    SqlConnection conn = new SqlConnection(cnnstr);
                    conn.Open();
                   SqlCommand comm = new SqlCommand();
                    comm.Connection = conn;
                

                    string sql = "insert into a values('01',@image)";
                    comm.CommandType = CommandType.Text;
                    comm.CommandText = sql;
                    comm.Parameters.Add("image", SqlDbType .Image   , imgbt.Length);
                    comm.Parameters[0].Value = imgbt;
                    comm.ExecuteNonQuery();
                    conn.Close();
            }

    再读取出来

                SqlDataReader dr = comm.ExecuteReader();
                          while (dr.Read())
                {
                    if (dr["imagetest"] != DBNull.Value)    
                    {
                        MemoryStream ms = new MemoryStream((byte[])dr["imagetest"]);//把照片读到MemoryStream里      
                        Image imageBlob = Image.FromStream(ms, true);//用流创建Image  
                        
                        pictureBox1.Image = imageBlob;//输出图片      
                    }
                    else//照片字段里没值,清空pb      
                    {
                        pictureBox1.Image = null;
                    }
                }

  • 相关阅读:
    js获取当前时间日期
    js操作Cookie
    C#常用正则表达式
    jquery操作select、radio、checkbox表单元素
    js实现页面跳转的几种方式
    js获取页面宽高大小
    c++写一个类后编译发现class重定义
    vtkMultiThreader坑爹吗?
    vtkStandardNewMacro()出现错误的问题
    转:将CFormView嵌入到CDockablePane中
  • 原文地址:https://www.cnblogs.com/qinweizhi/p/5646207.html
Copyright © 2011-2022 走看看