当前位置:首页 > 通信资讯 > 正文

c#怎么把图片存入数据库(C# 保存图片)

本文实例讲述了C#操作数据库中存取图片文件的方法。分享给大家供大家参考。具体如下:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 private string sqlconnstr = "Data Source=.;Database=db_test;User id=sa;PWD=123456"; /*功能:把一种图片插入到数据库中 *返回值:无 */ void InsertImageToDB() { //将需要存储的图片读取为数据流 FileStream fs = new FileStream(@"D:/Bear.jpg", FileMode.Open, FileAccess.Read); Byte[] byte_fs = new byte[fs.Length]; fs.Read(byte_fs, 0, Convert.ToInt32(fs.Length)); fs.Close(); //建立数据库连接 SqlConnection conn = new SqlConnection(sqlconnstr); conn.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandText = "insert into tb_test(image_id,image_file) values(@image_id,@image_file)"; SqlParameter[] param = new SqlParameter[2]; param[0] = new SqlParameter("@image_id", SqlDbType.Int); param[0].Value = 1; param[1] = new sqlParameter("@image_file", SqlDbType.Image); param[1].Value = byte_fs; for (int index = 0; index < 2; index++) { cmd.Parameters.Add(param[i]); } //执行SQL语句 cmd.ExecuteNonQuery(); conn.Close(); } /*功能:从数据库中读取图像文件,并显示在PictureBox控件中 *返回值:无 */ void GetImageFromDB() { byte[] Data = new byte[0]; //建立数据库连接 SqlConnection conn = new SqlConnection(sqlconnstr); conn.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandText = "select * from tb_parent"; SqlDataReader sdr = cmd.ExecuteReader(); sdr.Read(); Data = (byte[])sdr["parent_image"];//读取第一个图片的位流 MemoryStream mystream = new MemoryStream(Data); //用指定的数据流来创建一个image图片 System.Drawing.Image picbImage = System.Drawing.Image.FromStream(mystream, true); mystream.Close(); picturebox1.Image = picbImage; conn.Close(); }

希望本文所述对大家的C#程序设计有所帮助。

如果您对该产品感兴趣,请填写办理(客服微信:xiaoxiongyidong)

为您推荐:

发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。