VS.C#如何向数据数据库中存入和读取图片的

写入图片部分代码:
假设图片为 test.gif
byte [] bytes = File.ReadAllBytes(@"c:\test.gif");
SqlConnection con = new SqlConnection("server=.;uid=sa;pwd=xxx;database=数据库名");
con.open();
SqlCommand cmd = new SqlCommand("insert into 表(图片字段) values(@image)");
cmd.Parameters.Add("@image", SqlDbType.Image).Value = bytes;
cmd.ExecuteNonQuery();
读取部分代码:
SqlConnection con = new SqlConnection("server=.;uid=sa;pwd=xxx;database=数据库名");
con.open();
SqlCommand cmd = new SqlCommand("select 图片字段 表 where 图片编号=1");
object scalar = scmd.ExecuteScalar();
byte[] bytes=(byte[])scalar;

如果保存成文件:
File.WriteAllBytes(@"c:\read.gif",bytes);
如果要直接用网页输出:
MemoryStream ms = new MemoryStream(bytes);
Response.ContentType = "image/gif";
System.Drawing.Image image=System.Drawing.Image.FromStream(ms);
image.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
Response.End();

posted @ 2018-07-18 23:00  net-sky  阅读(903)  评论(0编辑  收藏  举报