C#保存图片到数据库并读取显示图片的方法
复制代码 代码如下: private void button2_Click_1(object sender,System.EventArgs e) { string pathName; if (this.openFileDialog1.ShowDialog()==System.Windows.Forms.DialogResult.OK) { pathName = this.openFileDialog1.FileName; System.Drawing.Image img = System.Drawing.Image.FromFile(pathName); this.pictureBox1.Image = img; //将图像读入到字节数组 System.IO.FileStream fs = new System.IO.FileStream(pathName,System.IO.FileMode.Open,System.IO.FileAccess.Read); byte[] buffByte = new byte[fs.Length]; fs.Read(buffByte,(int)fs.Length); fs.Close(); fs = null; //建立Command命令 string comm = @"Insert into table1(img,name) values(@img,@name)"; this.sqlCommand1 = new System.Data.SqlClient.SqlCommand (); this.sqlCommand1.CommandType = System.Data.CommandType.Text ; this.sqlCommand1.CommandText = comm; this.sqlCommand1.Connection = this.sqlConnection1 ; //创建Parameter this.sqlCommand1.Parameters.Add("@img",System.Data.SqlDbType.Image); this.sqlCommand1.Parameters[0].Value = http://www.aspzz.cn/ianakin/archive/2012/02/02/buffByte; this.sqlCommand1.Parameters.Add("@name",System.Data.SqlDbType.VarChar); this.sqlCommand1.Parameters[1].Value =http://www.aspzz.cn/ianakin/archive/2012/02/02/pathName.Substring(pathName.LastIndexOf("")+1); try { this.sqlConnection1.Open(); this.sqlCommand1.ExecuteNonQuery(); this.sqlConnection1.Close(); } catch(System.Exception ee) { MessageBox.Show(ee.Message ); } buffByte = null; this.FillListBox(); } 读取: 从数据库读图片到picturebox 复制代码 代码如下: SqlConnection conn=new SqlConnection(@"data source=chenyuming2004VSdotNET;uid=sa;pwd=cym;database=lhf"); conn.Open(); SqlCommand cmd=new SqlCommand("select 照片 from fuser where password='1b'",conn); SqlDataReader reader=cmd.ExecuteReader(); reader.Read(); MemoryStream buf=new MemoryStream((byte[])reader[0]); Image image=Image.FromStream(buf,true); pictureBox1.Image=image; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- 正则表达式实现将MM/DD/YYYY格式的日期转换为YYYY-MM-DD格式
- cocos2dx Physics 物理世界
- c# – EF6 Linq Query.仅包含返回子表的第一个条目
- 如何在PostgreSQL中临时禁用触发器?
- sqlite 's readme for sqlite3-doc package
- oracle – 使用非常大的文本数据和CLOB列
- xcode – 在Interface Builder中没有显示autoresizingmask功
- 程序单词
- JSON.parse()和JSON.stringify()
- ruby-on-rails – 尝试在RSpec has_selector行中使用正则表