c#存儲圖片到數據庫讀數據庫顯示圖片實例

 


這是一枚純粹的實例,裏面有些跟數據庫交互的地方,比如某個值,是隨便給你的,演示而已.

既然要顯示,還是用個簡單的winForm吧

-----------------------------------------------------------------

數據庫:

庫名字:test

表名字:testPic

字段:picName nvarchar(50),pic image

---------------------------------------------------------------

窗體

一個pictureBox,兩個button,名字不改,一個button1是上傳button2是查詢

一個openFileDialog 用於上傳時候選擇文件

--------------------------------------------------------------

請看代碼註釋

 

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

        private void button1_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "jpg|*jpg|bmp|*bmp|gif|*gif|png|*png";//過濾文件

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string FileFullPath = openFileDialog1.FileName;//取到圖片文件的路徑
                pictureBox1.LoadAsync(FileFullPath);//把圖片加載到界面的圖片框上
                FileStream fs = new FileStream(FileFullPath, FileMode.Open, FileAccess.Read);//用文件流來開啓這個圖片
                byte[] img = new byte[fs.Length];//實例化一個能夠裝下這個圖片的字節數組
                BinaryReader br = new BinaryReader(fs);//使用二進制讀取器實例讀取這個圖片文件
                img = br.ReadBytes(Convert.ToInt32(fs.Length));//用讀取器的讀取字節方法把圖片讀進之前的img數組
                SqlConnection sc = new SqlConnection(@"server=192.168.1.185;database=test;user id=my;password=4321");//連接數據庫
                sc.Open();//建立連接
                SqlCommand cmd = new SqlCommand(@"insert into pictest values(@picName,@pic)",sc);//用一個數據庫sql命令來插入一條記錄
                SqlParameter[] sp = new SqlParameter[2];//實例化兩個參數,分別是兩個字段的值
                sp[0] = new SqlParameter("@picName","logo");
                sp[1] = new SqlParameter("@pic",img);//字節數組對應了圖片
                cmd.Parameters.AddRange(sp);
                cmd.ExecuteNonQuery();//執行這個命令
                sc.Close();//管理數據連接
                MessageBox.Show("上傳成功");
 
            }
        }

        //讀取
        private void button2_Click(object sender, EventArgs e)
        {
            SqlConnection sc = new SqlConnection(@"server=192.168.1.185;database=test;user id=kx;password=4321");
            sc.Open();
            SqlCommand cmd = new SqlCommand(@"select * from picTest where picName=@picName", sc);
            SqlParameter[] sp = new SqlParameter[1];
            sp[0] = new SqlParameter("@picName", "logo");        
            cmd.Parameters.AddRange(sp);
            SqlDataAdapter sa = new SqlDataAdapter(cmd);//使用數據填充器查詢數據
            DataSet ds = new DataSet();            
            sa.Fill(ds, "tablename");          //放到數據集
            MemoryStream ms=new MemoryStream((byte[])ds.Tables[0].Rows[0][1]);//使用內存流直接在內存中把圖片字段的值轉化成字節數組後實例化這個內存流
            pictureBox1.Image = Image.FromStream(ms);//把這個內存流用image的靜態方法,fromStream賦值給圖片框的image屬性
            ms.Close();//關閉內存流
            sc.Close();//關閉連接
        }
    }


 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章