崔曉鴻 廊坊師範學院資訊科技提高班 十四期
阿新 • • 發佈:2018-12-12
圖片上傳到資料庫
圖片以二進位制的形式傳到資料庫,具體圖片檔案會放到一個指定的Image資料夾
1、先上傳到介面上
if (openFileDialog1.ShowDialog() == DialogResult.OK) { //PictureBox控制元件顯示圖片 picPhoto.Load(openFileDialog1.FileName); //獲取使用者選擇檔案的字尾名 string extension = Path.GetExtension(openFileDialog1.FileName); //宣告允許的字尾名 string[] str = new string[] { ".gif", ".jpge", ".jpg", ".png" }; if (!str.Contains(extension)) { MessageBox.Show("僅能上傳gif,jpge,jpg格式的圖片!"); } else { //獲取使用者選擇的檔案,並判斷檔案大小不能超過20K,fileInfo.Length是以位元組為單位的 FileInfo fileInfo = new FileInfo(openFileDialog1.FileName); if (fileInfo.Length > 20480) { MessageBox.Show("照片上傳成功!"); } else { //絕對路徑 string image = openFileDialog1.FileName; // 是指XXX.jpg string picpath = openFileDialog1.SafeFileName; File.Copy(openFileDialog1.FileName, Application.StartupPath + "\\Image\\" + picpath); } } }
2、然後獲取圖片轉換成二進位制放到資料庫
//獲取當前選擇的圖片 this.picPhoto.Image = Image.FromStream(this.openFileDialog1.OpenFile()); //獲取當前圖片的路徑 string path = openFileDialog1.FileName.ToString(); //將制定路徑的圖片新增到FileStream類中 FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); //通過FileStream物件例項化BinaryReader物件 BinaryReader br = new BinaryReader(fs); //通過BinaryReader類物件的ReadBytes()方法將FileStream類物件轉化為二進位制陣列 byte[] imgBytesIn = br.ReadBytes(Convert.ToInt32(fs.Length)); user.Photo = imgBytesIn;
從資料庫中調取圖片並顯示
介面上需要有一個PictureBox的控制元件用來放圖片 想通過SQL語句查到記錄放到list中,然後直接取list中的圖片
List<UserInfo> ulist = UFacade.SelectUserByUserID(user);
byte[] images = (byte[])ulist[0].Photo;
MemoryStream ms = new MemoryStream(images);
Bitmap bmp = new Bitmap(ms);
picPhoto.Image = bmp;