WPF实现的图片保存显示有些不一样,有必要自我总结一下。。。
【注:数据库中保存图片的数据类型最好是varbiary(max)】
1.图片预览功能:
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.以流的方式将图片保存在数据库
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.从数据库中读取以流的方式显示
1 private void dataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e) 2 { 3 if ((e.OriginalSource as DataGrid).SelectedItem != null) 4 { 5 int job_id = Convert.ToInt32(((e.OriginalSource as DataGrid).SelectedItem as DataRowView)[0].ToString()); 6 DataSet ds = DBHelper.DBSQLHelper.Search("select * from myjobs where job_id=" + job_id, null, CommandType.Text); 7 this.tb_jobdesc.Text = ds.Tables[0].Rows[0]["job_desc"].ToString(); 8 byte[] img = (byte[])ds.Tables[0].Rows[0]["pic"]; //从数据库中获取图片数据转换为字节数组(注意:不用用这种方式转换为字节数组,这种转换有问题,我之前一直出不来效果 byte[] img = System.Text.ASCIIEncoding.ASCII.GetBytes(ds.Tables[0].Rows[0]["pic"].ToString()); 现在修改了,就能出来效果了,这个问题还挺让人纠结的呢,所以大家要注意哦!) 9 ShowSelectedIMG(img); //以流的方式显示图片的方法 10 } 11 } 12 private void ShowSelectedIMG(byte[] img) 13 { 14 System.IO.MemoryStream ms = new System.IO.MemoryStream(img);//img是从数据库中读取出来的字节数组 15 ms.Seek(0, System.IO.SeekOrigin.Begin); 16 17 BitmapImage newBitmapImage = new BitmapImage(); 18 newBitmapImage.BeginInit(); 19 newBitmapImage.StreamSource = ms; 20 newBitmapImage.EndInit(); 21 image1.Source = newBitmapImage; 22 }
哈哈,拥有以上这几步,图片预览、保存、显示基本就可实现了!!!(有兴趣的可以试试哦!有啥问题相互交流哦!)
本文来自wy926的博客,原文地址:http://www.cnblogs.com/wyuan/archive/2012/05/22/2513103.html