C#:將圖片文件上傳到數據庫兩種方法。


(推薦)方法1:

將圖片復制到指定文件夾,在數據庫中存儲圖片路徑,通過讀取路徑來顯示圖片。

string str;
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                str = openFileDialog1.FileName;
                pictureBox1.Image = Image.FromFile(str);
            }
        }//打開文件並在PictureBox中顯示圖片

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            string filename = DateTime.Now.Ticks.ToString();//時間戳,保證圖片名稱不重復
            string name = @"F:\數據庫作業\外賣\外賣\外賣\bin\Debug\image\" + filename;
            File.Copy(str, name);//將圖片復制到指定文件夾
            _users.Domain(name);//利用SQL將文件路徑上傳至數據庫
        }
        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            var info = _users.SelectDomain();//SQL查詢路徑
            pictureBox1.Image = Image.FromFile(info.Rows[0][0].ToString());//顯示照片
            this.pictureBox1.Refresh();
        }

 

方法2:

將圖片讀成二進制后上傳至數據庫,再將二進制數據轉化成圖片。

string str;
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                str = openFileDialog1.FileName;
                pictureBox1.Image = Image.FromFile(str);
            }
            
        }//打開文件並在PictureBox中顯示圖片

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            FileStream fs = new FileStream(str, FileMode.Open, FileAccess.Read);
            BinaryReader br = new BinaryReader(fs);
            byte[] imgBytesIn = br.ReadBytes(Convert.ToInt32(fs.Length));//轉成二進制數據的操作
            _users.Domain(imgBytesIn);
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            var table = _users.SelectDomain();
            byte[] imagedata = (byte[])(table.Rows[0][0]);
            MemoryStream myStream = new MemoryStream(imagedata);//轉成圖片
            pictureBox1.Image = Image.FromStream(myStream);//顯示圖片
        }

    }

 圖片自適應picturebox用Sizemode-Stretchimage(PictureBox屬性修改)。


免責聲明!

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



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