數據庫對圖片的存儲和讀取


數據庫中關於二進制類型的介紹:
 
  binary
  固定長度的二進制數據,其最大長度為 8,000 個字節。
  varbinary
  可變長度的二進制數據,其最大長度為 8,000 個字節。
  image

  可變長度的二進制數據,其最大長度為 2^31 - 1 (2,147,483,647) 個字節

 

  二進制類型主要用來存儲圖片,PDF文檔等二進制文件,通常情況下,可以將圖片,PDF文檔都可以存儲在文件系統中,然后在數據庫中存儲這些文件的路徑,這種方式存儲比直接存儲在數據庫中簡單,但是訪問速度比存儲在數據庫中慢。實際編碼中,使用二進制類型並不多。

 

eg: 使用數據庫存儲讀取圖片的例子

//上傳圖片
private void btnUpload_Click(object sender, EventArgs e)
{
  try
  {
    string filePath = "";
    byte[] bytes = null;
    FileStream fs = null;
    filePath = pictureBox1.ImageLocation;
    if (string.IsNullOrWhiteSpace(filePath))
    {
      MessageBox.Show("...");
      return;
    }
    if (filePath.ToLower().Contains(".png") || filePath.ToLower().Contains(".jpg"))
    {
      fs = new FileStream(filePath, FileMode.Open);
      bytes = new byte[fs.Length];
      fs.Read(bytes, 0, bytes.Length);
      using (SqlConnection con = new SqlConnection(
        "Data Source=.;Initial Catalog=TestDB;Integrated Security=True;"))
      {
        con.Open();
        SqlCommand cmd = new SqlCommand($"INSERT INTO ImageStore (image,file_path,file_name) VALUES           (@image,@file_path,@file_name)", con);
        cmd.CommandType = CommandType.Text;
        SqlParameter para1 = new SqlParameter("@image", SqlDbType.Image);
        SqlParameter para2 = new SqlParameter("@file_path", SqlDbType.NVarChar);
        SqlParameter para3 = new SqlParameter("@file_name", SqlDbType.NVarChar);
        para1.Value = bytes;
        para2.Value = filePath;
        para3.Value = filePath.Split('\\')[filePath.Split('\\').Length - 1];
        cmd.Parameters.Add(para1);
        cmd.Parameters.Add(para2);
        cmd.Parameters.Add(para3);
        int res = cmd.ExecuteNonQuery();
        if (res > 0) MessageBox.Show("SUCCESS");
        if (res <= 0) MessageBox.Show("ERROR");
      }
    }
    else
    {
      MessageBox.Show("ERROR");
    }

    }
    catch (Exception)
    {

      throw;
    }
  }

 

//打開文件
private void btnOpen_Click(object sender, EventArgs e)
{
  try
  {
    string filePath = "";
    OpenFileDialog openFile = new OpenFileDialog();
    openFile.Title = "Upload image";
    openFile.Filter = "All Files|*.*|PNG|*.png|JPG|*.jpg";
    DialogResult dr = openFile.ShowDialog();
    if (dr == DialogResult.OK)
    {
      filePath = openFile.FileName;
      pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
      pictureBox1.ImageLocation = filePath;
    }
  }
  catch (Exception)
  {

      throw;
    }
  }

 

//下載圖片
private void btnDownLoad_Click(object sender, EventArgs e)
{
  FileStream fs = null;
  SqlDataAdapter adapter = null;
  string filePath = AppDomain.CurrentDomain.BaseDirectory + "temp.jpg";
  try
  {
    DataSet ds = new DataSet();
    byte[] bytes = null;
    //byte[] bytesRead = new byte[2048];
    //string strByte = null;
    using (SqlConnection con = new SqlConnection(
      "Data Source=.;Initial Catalog=TestDB;Integrated Security=True;"))
    {
      con.Open();
      SqlCommand cmd = new SqlCommand("SELECT * FROM ImageStore WHERE id = 4", con);
      cmd.CommandType = CommandType.Text;
      adapter = new SqlDataAdapter(cmd);
      adapter.Fill(ds);
      if (ds.Tables[0].Rows.Count <= 0)
      {
        MessageBox.Show("ERROR");
        return;
      }
      else
      {
        bytes = (byte[])ds.Tables[0].Rows[0]["image"];
        if (bytes.Length > 0)
        {
          if (File.Exists(filePath))
          {
            File.Delete(filePath);
          }
          fs = new FileStream(filePath, FileMode.OpenOrCreate);
          for (int i = 0; i < bytes.Length; i++)
          {
            fs.WriteByte(bytes[i]);
          }
        }
        pictureBox2.ImageLocation = filePath;
        pictureBox2.SizeMode = PictureBoxSizeMode.Zoom;
      }
    }
  }
  catch (Exception)
  {

      throw;
    }
    finally
    {
      if (fs != null)
      {
        fs.Close();
      }
      if (adapter != null)
      {
        adapter.Dispose();
      }
    }
  }

 

  

  在使用數據庫結束后,一定要關閉FileStream對象、SqlDataAdapter對象、SqlConnection等。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM