您好,欢迎访问一九零五行业门户网

PictureBox中的Image对象转存到数据库

这个是在百度知道上回答问题时看到的,一时没有做出来,看了一些资料才弄清楚的。 主要有两个点: 1.对流的操作不熟悉,不知道图片image对象是可以”保存“到memorystream中的; image.save(mstream, system.drawing.imaging.imageformat.jpeg); 2.二进制数
这个是在百度知道上回答问题时看到的,一时没有做出来,看了一些资料才弄清楚的。
主要有两个点:
1.对流的操作不熟悉,不知道图片image对象是可以”保存“到memorystream中的;
image.save(mstream, system.drawing.imaging.imageformat.jpeg);
2.二进制数据插入到数据库的操作不清楚。
sqlparameter param = new sqlparameter(imgdata, sqldbtype.varbinary, imagebytes.length);param.value = imagebytes;cmd.parameters.add(param);
下面贴上代码
private void button1_click(object sender, eventargs e) { byte[] imagebytes = getimagebytes(picturebox1.image); string connstr = sql server连接字符串; using (sqlconnection conn = new sqlconnection(connstr)) { string sql = insert into t_img values (@imgdata) ; using (sqlcommand cmd = new sqlcommand(sql)) { sqlparameter param = new sqlparameter(imgdata, sqldbtype.varbinary, imagebytes.length); param.value = imagebytes; cmd.parameters.add(param); cmd.connection = conn; conn.open(); int i = cmd.executenonquery(); messagebox.show(i.tostring()); } } } private byte[] getimagebytes(image image) { memorystream mstream = new memorystream(); image.save(mstream, system.drawing.imaging.imageformat.jpeg); byte[] bytedata = new byte[mstream.length]; mstream.position = 0; mstream.read(bytedata, 0, bytedata.length); mstream.close(); return bytedata; }
上传了源代码:http://download.csdn.net/detail/frombegintoend/4403728
其它类似信息

推荐信息