C#保存图片到数据库并读取显示图片的方法
private void button2_click_1(object sender, system.eventargs e)
{
string pathname;
if (this.openfiledialog1.showdialog()==system.windows.forms.dialogresult.ok)
{
pathname = this.openfiledialog1.filename;
system.drawing.image img = system.drawing.image.fromfile(pathname);
this.picturebox1.image = img;
//将图像读入到字节数组
system.io.filestream fs = new system.io.filestream(pathname,system.io.filemode.open,system.io.fileaccess.read);
byte[] buffbyte = new byte[fs.length];
fs.read(buffbyte,0,(int)fs.length);
fs.close();
fs = null;
//建立command命令
string comm = @"insert into table1(img,name) values(@img,@name)";
this.sqlcommand1 = new system.data.sqlclient.sqlcommand ();
this.sqlcommand1.commandtype = system.data.commandtype.text ;
this.sqlcommand1.commandtext = comm;
this.sqlcommand1.connection = this.sqlconnection1 ;
//创建parameter
this.sqlcommand1.parameters.add("@img",system.data.sqldbtype.image);
this.sqlcommand1.parameters[0].value = //www.jb51.net/ianakin/archive/2012/02/02/buffbyte;
this.sqlcommand1.parameters.add("@name",system.data.sqldbtype.varchar);
this.sqlcommand1.parameters[1].value =//www.jb51.net/ianakin/archive/2012/02/02/pathname.substring(pathname.lastindexof("\\")+1);
try
{
this.sqlconnection1.open();
this.sqlcommand1.executenonquery();
this.sqlconnection1.close();
}
catch(system.exception ee)
{
messagebox.show(ee.message );
}
buffbyte = null;
this.filllistbox();
}
读取:
从数据库读图片到picturebox
sqlconnection conn=new sqlconnection(@"data source=chenyuming2004vsdotnet;uid=sa;pwd=cym;database=lhf");
conn.open();
sqlcommand cmd=new sqlcommand("select 照片 from fuser where password='1b'",conn);
sqldatareader reader=cmd.executereader();
reader.read();
memorystream buf=new memorystream((byte[])reader[0]);
image image=image.fromstream(buf,true);
picturebox1.image=image;