C#操作图片读取和存储SQLserver实现代码
程序员文章站
2023-12-14 08:44:40
一、用c#将image转换成byte[]并插入数据库: 1.1 将图片控件的image转换成流: 复制代码 代码如下: private byte[] pictoarray(...
一、用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);
}
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);
}