logo资料库

C#操作图片读取和存储SQLserver实现代码.pdf

第1页 / 共2页
第2页 / 共2页
资料共2页,全文预览结束
操作图片读取和存储SQLserver实现代码 实现代码 C#操作图片读取和存储 用C#将Image转换成byte[]并插入数据库/将图片数据从SQLserver中取出来并显示到pictureBox控件上,接下来 将为你详细介绍下实现步骤,感兴趣的你可以参考下 一、用C#将Image转换成byte[]并插入数据库: 1.1 将图片控件的Image转换成流: 复制代码 代码如下: private byte[] PicToArray() { Bitmap bm = new Bitmap(picBox.Image); MemoryStream ms = new MemoryStream(); bm.Save(ms, ImageFormat.Jpeg); return ms.GetBuffer(); } 复制代码 代码如下:             //保存到数据库       try { string sql = "update T_Employee set ImageLogo=@ImageLogo where EmpId=@EmpId"; SqlHelper.ExecuteNonQuery(sql, new SqlParameter("@ImageLogo", imgSourse)); MessageBox.Show("修改已保存!");// ShowInfo(0); } catch (Exception ex) { MessageBox.Show("更新失败!" + ex.Message); return; } 1.2将图片文件转换成字节流并插入数据库: 复制代码 代码如下: class ImageInserter { public static int InsertImg(string path) { //----------以文件的方式读取图片并转化成字节流 FileStream fs = new FileStream(path,FileMode.Open); byte[] imgSourse = new byte[fs.Length]; fs.Read(imgSourse,0,imgSourse.Length); fs.Close(); using (SqlConnection conn = new SqlConnection(SqlHelper.connStr)) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = "update T_Employee set ImageLogo=@ImageLogo"; // cmd.Parameters.Add("@ImageLogo", SqlDbType.Image); cmd.Parameters.Add(new SqlParameter("@ImageLogo", imgSourse)); return cmd.ExecuteNonQuery(); } } } 二、将图片数据从SQLserver中取出来并显示到pictureBox控件上: 复制代码 代码如下:        byte[] ImageLogoArray = row["ImageLogo"] is DBNull ? null :(byte[])(row["ImageLogo"]); MemoryStream ms=null; if (ImageLogoArray!=null) { ms = new MemoryStream(ImageLogoArray); picBox.Image = new Bitmap(ms);
}
分享到:
收藏