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;
                    }
                }

  • 相关阅读:
    Spring Boot 配置元数据指南
    面试中常被提到的最左前缀匹配原则
    MyBatis缓存机制(一级缓存,二级缓存)
    计算机网络基础知识
    垃圾收集算法与垃圾收集器
    递归与分治策略
    五种IO模型和BIO,NIO,AIO
    七种阻塞队列
    ConcurrentHashMap(1.7版本和1.8版本)
    重入锁 ReentrantLock
  • 原文地址:https://www.cnblogs.com/qinweizhi/p/5646207.html
Copyright © 2011-2022 走看看