C# 儲存影像檔到SQL SERVER資料庫,再讀取該檔案並顯示

來源:互聯網
上載者:User

 需要在SQL SERVER中建立資料庫test, 然後再test中建立一個資料表ImageTable,
含欄位 id  int  自動成長
ImagePath  nchar(50)
Image    image類型

代碼如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;

namespace SaveImageToSqlServer
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void buttonSaveImageToDataServer_Click(object sender, EventArgs e)
        {
            this.folderBrowserDialog1.ShowDialog();

            string dirName = this.folderBrowserDialog1.SelectedPath;
            DirectoryInfo dir = new DirectoryInfo(dirName);
            FileInfo[] fileInfos = dir.GetFiles("*.jpg");                     //擷取檔案夾下所有jpg檔案,因為影像檔都很大的,選取檔案夾下不要有太多圖片,否則Primary區會滿了,系統會提示無法再插入資料。
            List<string> fileList = new List<string>(100);   
            foreach (FileInfo fileInfo in fileInfos)
            {
                fileList.Add(fileInfo.FullName);
                System.Windows.Forms.Application.DoEvents();
            }

            #region Save data to Data Server
            string strConn =                              // 設定連接字串,我是在本機上串連,遠端話需要修改連接字串
                @"Server=(local);"
            + @"Initial Catalog=test;"
            + @"User Id =fisherman;"
            + @"Password=;"
            + @"Integrated Security = true";

            try
            {
                using (SqlConnection sqlConnection = new SqlConnection(strConn))    // 使用using 可以及時釋放資源
                {
                    sqlConnection.Open();
                    foreach (string file in fileList)
                    {
                        // 影像檔存放在資料庫中,需要先轉換成二進位流。使用byte【】來儲存。
                        FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
                        byte[] byteImage = new byte[fileStream.Length];
                        fileStream.Read(byteImage, 0, (int)fileStream.Length);
                        
                       //平時寫代碼,對於Insert語句,喜歡直接用“Insert into tableName(a,b)Values(a1,b1)” 是完成,但是對於二進位流,這樣寫
                        // 會報錯,必須按照下面的方式,設定參數名稱類型。
                        string commandText = "Insert into ImageTable(ImagePath, Image)Values(@ImagePath, @Image)";
                        SqlCommand sqlCommand = new SqlCommand(commandText, sqlConnection);
                        sqlCommand.Parameters.Add("@ImagePath", SqlDbType.Text);      // 影像檔路徑
                        sqlCommand.Parameters.Add("@Image", SqlDbType.Binary);         // 影像檔資料,使用二進位格式。
                        sqlCommand.Parameters["@ImagePath"].Value = file;
                        sqlCommand.Parameters["@Image"].Value = byteImage;              // 將映像賦值給command

                        sqlCommand.ExecuteNonQuery();                   

                        System.Windows.Forms.Application.DoEvents();
                    }
                  sqlConnection.Close();       // 用完之後,必須顯示關閉
                }
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.ToString());
            }
            #endregion
            MessageBox.Show("Save data OK.");
        }

        private void buttonShowImage_Click(object sender, EventArgs e)
        {
            // 連接字串,同上
            string strConn =
                @"Server=(local);"
            + @"Initial Catalog=test;"
            + @"User id=fisherman;"
            + @"Password=;"
            + @"Integrated Security=true;";

            try
            {
                using (SqlConnection sqlConnection = new SqlConnection(strConn))
                {
                    sqlConnection.Open();
                    string commandText = "Select ImagePath, Image from ImageTable";     // 查詢ImageTable中的資料
                    SqlDataAdapter adapter = new SqlDataAdapter(commandText, sqlConnection);   // 使用DataTable來儲存資料,以便賦值給DataGridView, 函數結束後,表單上的DataGridView會顯示,2列,一列是Image。
                    // Row和Column間距太小,不太好看,不過至少圖片能夠顯示。
                    DataTable dt = new DataTable();
                    adapter.Fill(dt);
                    this.dataGridView1.DataSource = dt;
                    sqlConnection.Close();
                }
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.