WPF实现的图片保存显示有些不一样,有必要自我总结一下。。。
【注:数据库中保存图片的数据类型最好是varbiary(max)】
1.图片预览功能:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 private void btn_preview_Click(object sender, RoutedEventArgs e) 2 { 3 OpenFileDialog openfiledialog = new OpenFileDialog(); 4 openfiledialog.Filter = "图片(*.jpg;*.png;*.gif;*.bmp;*.jpeg)|*.jpg;*.png;*.gif;*.bmp;*.jpeg"; 5 if ((bool)openfiledialog.ShowDialog()) 6 { 7 BitmapImage bitmapimg = new BitmapImage(new Uri(openfiledialog.FileName)); 8 image1.Source = bitmapimg; 9 //image1.Width = bitmapimg.Width; 10 //image1.Height = bitmapimg.Height; 11 this.tb_selPic.Text = openfiledialog.FileName; 12 } 13 }
2.以流的方式将图片保存在数据库
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 private void btn_add_Click(object sender, RoutedEventArgs e) 2 { 3 if (!string.IsNullOrEmpty(this.tb_selPic.Text)) 4 { 5 byte[] img = File.ReadAllBytes(this.tb_selPic.Text); //将图片装换为字节,存储在数据库中 6 MyJobs myJobs = new MyJobs 7 { 8 Job_desc = this.tb_jobdesc.Text, 9 Pic = img, 10 }; 11 List<SqlParameter> sqlPar = new List<SqlParameter> 12 { 13 new SqlParameter("@job_desc",myJobs.Job_desc), 14 new SqlParameter("@pic",myJobs.Pic), 15 }; 16 string msg = DBHelper.DBSQLHelper.Execute("proc_myjobs", sqlPar, System.Data.CommandType.StoredProcedure) > 0 ? "添加成功!":"添加失败!"; 17 MessageBox.Show(msg); 18 } 19 else 20 { 21 MessageBox.Show("请选择图片!"); 22 } 23 }
3.从数据库中读取以流的方式显示
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 private void dataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e) { if ((e.OriginalSource as DataGrid).SelectedItem != null) { int job_id = Convert.ToInt32(((e.OriginalSource as DataGrid).SelectedItem as DataRowView)[0].ToString()); DataSet ds = DBHelper.DBSQLHelper.Search("select * from myjobs where job_id=" + job_id, null, CommandType.Text); this.tb_jobdesc.Text = ds.Tables[0].Rows[0]["job_desc"].ToString(); byte[] img = (byte[])ds.Tables[0].Rows[0]["pic"]; //从数据库中获取图片数据转换为字节数组(注意:不用用这种方式转换为字节数组,这种转换有问题,我之前一直出不来效果 byte[] img = System.Text.ASCIIEncoding.ASCII.GetBytes(ds.Tables[0].Rows[0]["pic"].ToString()); 现在修改了,就能出来效果了,这个问题还挺让人纠结的呢,所以大家要注意哦!) ShowSelectedIMG(img); //以流的方式显示图片的方法 } } 2 3 private void ShowSelectedIMG(byte[] img) { System.IO.MemoryStream ms = new System.IO.MemoryStream(img);//img是从数据库中读取出来的字节数组 4 5 ms.Seek(0, System.IO.SeekOrigin.Begin); BitmapImage newBitmapImage = new BitmapImage(); 6 7 newBitmapImage.BeginInit(); 8 9 newBitmapImage.StreamSource = ms; 10 11 newBitmapImage.EndInit(); 12 13 image1.Source = newBitmapImage; }