下面是 access 的示例,sql server 你需要调整一下。字段类型可以设置为binary(max) 或 image
-
///
-
///c#以二进制方式存储图片到access数据库中
-
///将指定的图片信息存入到 access 数据库
-
///
-
///图片名
-
///图片的 byte
-
public void insertimagetoaccess(string fimagename, byte[] fimagebinary)
-
{
-
// access 表// 字段// imagename 文本// imagebinary ole 对象
-
using(oledbconnection conn =newoledbconnection(“provider=microsoft.jet.oledb.4.0;data source=d:\\x.mdb”)){
-
oledbcommand finsertcommand =newoledbcommand();
-
finsertcommand.connection = conn;
-
finsertcommand.commandtext =”insert into images (imagename, imagebinary) values (?, ?)”;
-
finsertcommand.parameters.add(“@imagename”, oledbtype.varchar).value = fimagename;
-
finsertcommand.parameters.add(“@imagebinary”, oledbtype.binary, fimagebinary.length).value = fimagebinary;
-
conn.open();
-
finsertcommand.executenonquery();
-
}
-
}
-
-
///
-
///获取指定图片名的 byte
-
///
-
///图片名
-
///
-
public byte[] getimagefromaccess(string fimagename)
-
{
-
using(oledbconnection conn =newoledbconnection(“provider=microsoft.jet.oledb.4.0;data source=d:\\x.mdb”)){
-
oledbcommand fselectcommand =newoledbcommand();
-
fselectcommand.connection = conn;
-
fselectcommand.commandtext =”select imagebinary from images where imagename = ?”;
-
fselectcommand.parameters.add(“@imagename”, oledbtype.varchar).value = fimagename; conn.open();
-
object o = fselectcommand.executescalar();
-
return(o ==null?null: (byte[])o);
-
}
-
}
-
-
private void button1_click(objectsender, eventargs e){
-
using(openfiledialog dialog =newopenfiledialog()){
-
dialog.filter =”gif|*.gif”;
-
dialog.multiselect =false;
-
if(dialog.showdialog() == dialogresult.ok){
-
stringfimagename = path.getfilenamewithoutextension(dialog.filename);
-
filestream fs =newfilestream(dialog.filename, filemode.open, fileaccess.read);
-
binaryreader br =newbinaryreader(fs);
-
byte[] finputimagebinary = br.readbytes((int)fs.length);
-
br.close();
-
fs.close();
-
// 保存到数据库
-
this.insertimagetoaccess(fimagename, finputimagebinary);
-
// 从数据库获取图片并显示到 picturebox1
-
byte[] foutputimagebinary =this.getimagefromaccess(fimagename);
-
memorystream ms =newmemorystream(foutputimagebinary);
-
picturebox1.image = image.fromstream(ms);
-
}
-
}
-
}
阅读(1816) | 评论(0) | 转发(0) |