• 利用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;
                    }
                }

  • 相关阅读:
    一、定义枚举类,并随机取值
    常用Linux日志查询命令
    一、爬虫之基础
    Jmeter接口自动化-3-生成HTML报告
    Jmeter接口自动化-2-查看结果数只能显示有限的数据,查看全部数据
    Jmeter接口自动化-1-启动报错:Could not initialize class org.apache.jmeter.gui.util.MenuFactory
    三十一、Java基础之Collection集合
    设计模式
    缓存
    Ckeditor配置
  • 原文地址:https://www.cnblogs.com/qinweizhi/p/5646207.html
Copyright © 2020-2023  润新知