How to store pictures in SQL database and read pictures from database (solution)

 
table of Contents

1. Select a local picture and save it in the database

2.Save () method

3. Read photos from the database


Recently, the project needs to upload and download pictures. I thought about how to store pictures. You can store them in the database using local paths and binary data. Finally, we weighed the pros and cons and decided to store the pictures in the database. This article explains in detail how to store pictures in SQL database and how to read pictures from SQL database. Hope you can gain something! ! !

1. Select a local picture and save it in the database

/// <summary>
/// 将图片存进数据库
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
      //点击按钮弹出对话框
      //选中图片,为Img的属性
      OpenFileDialog ofd = new OpenFileDialog();  //打开文件
      ofd.Title = "请选择图片文件";//弹出框的标题
      ofd.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);//设置系统目录
      // ofd.InitialDirectory = @"C:\Users\Administrator\Pictures";//设置系统目录
      ofd.Filter = "(*.jpg)|*.jpg";

      if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
      {
          this.pictureBox1.Image = Image.FromStream(ofd.OpenFile());  //获取当前选择的图片
          string path = ofd.FileName.ToString(); //获取当前图片的路径
          FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); //将指定路径的图片添加到FileStream类中
          BinaryReader br = new BinaryReader(fs);//通过FileStream对象实例化BinaryReader对象

          byte[] imgBytesIn = br.ReadBytes(Convert.ToInt32(fs.Length));//将图片转为二进制数据
          Save(imgBytesIn);//调用(自己写的一个方法)

       }

}

2.Save () method

/// <summary>
/// 存进数据库
/// </summary>
/// <param name="imgBytesIn">二进制数据</param>
private void Save(byte[] imgBytesIn)
{
     try
    {   //连接数据库
         SqlConnection con = new SqlConnection("server=192.168.111.100;uid=sa;pwd=123456;database=Chargetest");//连接本地数据库
          con.Open();

          SqlCommand cmd = new SqlCommand("insert into image (Img_url) values(@Image);", con); //SQL语句
          cmd.Parameters.Add("@Image", SqlDbType.Image);
          cmd.Parameters["@Image"].Value = imgBytesIn;
          cmd.ExecuteNonQuery();

          con.Close();
          MessageBox.Show("图片上传成功");

    }
    catch
    {
         MessageBox.Show("您选择的图片不能被读取或文件类型不对!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);

         }

   }

3. Read photos from the database

/// <summary>
/// 从数据库读取图片
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
       byte[] MyData = new byte[0];
       using (SqlConnection conn = new SqlConnection("server=ZYB;Database =Chargetest; User ID = sa;Password =123456"))
      {
           conn.Open();
           SqlCommand cmd = new SqlCommand();
           cmd.Connection = conn;
           cmd.CommandText = "select * from image where Id=14"; //写自己要查图片的主键
           SqlDataReader sdr = cmd.ExecuteReader();
           sdr.Read();
           object o = sdr["img_url"];
           MyData = (byte[])sdr["img_url"];//读取第一个图片的位流
           MemoryStream memoryStream = null;
           memoryStream = new MemoryStream(MyData);
           pictureBox1.Image = Image.FromStream(memoryStream);//将图片赋给pictureBox1控件
           MessageBox.Show("读取成功");
              
       }
}

If this blog is helpful to you, please remember to leave a message + like it.

Guess you like

Origin blog.csdn.net/promsing/article/details/109493991