时间:2021-07-01 10:21:17 帮助过:2人阅读
实现示例:
//1.首先将图片装换成字节数组 Bitmap btm = new Bitmap("C:/Users/Desktop/1.jpg"); MemoryStream ms = new MemoryStream(); btm.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp); byte[] bytes = ms.GetBuffer(); //byte[] bytes= ms.ToArray(); 这两句都可以 ms.Close(); try{ //2.往数据库里写图片数据 //先打开两个类库文件 SqlConnection con = new SqlConnection(); con.ConnectionString = "server=.;database=Test;uid=sa;pwd=123456"; con.Open(); SqlCommand com = new SqlCommand(); com.Connection = con; com.CommandType = CommandType.Text; com.CommandText = "insert into Map(Id,BitmapData) values(1,@photo)"; com.Parameters.AddWithValue("@photo", bytes); SqlDataReader dr = com.ExecuteReader();//执行SQL语句 dr.Close();//关闭执行 con.Close();//关闭数据库 //3.从数据库中取图片数据并显示 SqlConnection con = new SqlConnection(); con.ConnectionString = "server=.;database=Test;uid=sa;pwd=123456"; String sql = "select * from Map where Id=1"; SqlCommand cmd = new SqlCommand(sql, con); con.Open(); using (SqlDataReader dr = cmd.ExecuteReader()) { if (dr.Read()){ if (!dr.IsDBNull(1))//防止照片字段为空 { System.Data.SqlTypes.SqlBytes dataBytes = dr.GetSqlBytes(1); Image imge= Image.FromStream(dataBytes.Stream);//显示照片 pb.ImageLocation = null; pb.Image = null; pb.Image = imge; } } } con.Close();//关闭数据库 } catch (Exception) { throw; }
上述为测试示例,没有直接取byte[]类型,如果要转化成byte[]类型,可以用如下方法:
byte[] b=dr.GetSqlBytes(1).Value;
byte[] b1 = dr.GetSqlBytes(1).Buffer;
数据库中用varbinary存储二进制数据
标签: