C#操作图片读取和存储SQLserver

用C#将Image转换成byte[]并插入sql数据库/将图片数据从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)) 
{  // www.jbxue.com
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); 
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值