欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#保存图片到数据库并读取显示图片的方法

程序员文章站 2023-12-18 18:25:16
复制代码 代码如下:private void button2_click_1(object sender, system.eventargs e) { string p...

复制代码 代码如下:

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;

上一篇:

下一篇: