欢迎来到天天文库
浏览记录
ID:57863275
大小:45.88 KB
页数:26页
时间:2020-09-02
《C#从SQL-数据库中读取和存入图片.docx》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、C#从SQL数据库中读取和存入图片本实例主要介绍如何将图片存入数据库。将图片存入数据库,首先要在数据库中建立一张表,将存储图片的字段类型设为Image类型,用FileStream类、BinaryReader把图片读成字节的形式,赋给一个字节数组,然后用ADO.SqlCommand对象的ExecuteNonQuery()方法来把数据保存到数据库中。主要代码如下: privatevoidbutton1_Click(objectsender,EventArgse) { openFileDia
2、log1.Filter="*jpg
3、*.JPG
4、*.GIF
5、*.GIF
6、*.BMP
7、*.BMP"; if(openFileDialog1.ShowDialog()==DialogResult.OK) { stringfullpath=openFileDialog1.FileName;//文件路径 FileStreamfs=newFileStream(fullpath,FileMode.Open); by
8、te[]imagebytes=newbyte[fs.Length]; BinaryReaderbr=newBinaryReader(fs); imagebytes=br.ReadBytes(Convert.ToInt32(fs.Length)); //打开数据库 SqlConnectioncon=newSqlConnection("server=(local);uid=sa;pwd=;database=db
9、_05"); con.Open(); SqlCommandcom=newSqlCommand("insertintotb_08values(@ImageList)",con); com.Parameters.Add("ImageList",SqlDbType.Image); com.Parameters["ImageList"].Value=imagebytes; com.Exec
10、uteNonQuery(); con.Close(); } }本实例主要介绍如何从数据库中把图片读出来。实现本实例主要是利用SqlDataReader从数据库中把Image字段值读出来,赋给一个byte[]字节数组,然后使用MemoryStream类与Bitmap把图片读取出来。主要代码如下: privatevoidbutton1_Click(objectsender,EventArgse) { byte[]image
11、bytes=null; //打开数据库 SqlConnectioncon=newSqlConnection("server=(local);uid=sa;pwd=;database=db_05"); con.Open(); SqlCommandcom=newSqlCommand("selecttop1*fromtb_09",con); SqlDataReaderdr=com.Execut
12、eReader(); while(dr.Read()) { imagebytes=(byte[])dr.GetValue(1); } dr.Close(); com.Clone(); con.Close(); MemoryStreamms=newMemoryStream(imagebyte
13、s); Bitmapbmpt=newBitmap(ms); pictureBox1.Image=bmpt; }本实例主要介绍如何只允许输入指定图片格式。用OpenFileDialog控件打开图片文件,只要将OpenFileDialog控件的Filter属性指定为特定的图片格式即
此文档下载收益归作者所有