01.void SaveImage(Image i)
02.{
03. byte[] buffer = null;
04. using (MemoryStream ms = new MemoryStream())
05. {
06. i.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
07. buffer = ms.ToArray();
08. }
09. using (SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=test;Integrated Security=True"))
10. {
11. using (SqlCommand cmd = new SqlCommand("insert into tab1 values(@image)", con))
12. {
13. cmd.Parameters.Add(new SqlParameter("@image", buffer));
14. con.Open();
15. cmd.ExecuteNonQuery();
16. }
17. }
18.}
19.
20.Image GetImage()
21.{
22. Image i = null;
23. using (SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=test;Integrated Security=True"))
24. {
25. using (SqlCommand cmd = new SqlCommand("select * from tab1", con))
26. {
27. con.Open();
28. using (SqlDataReader dr = cmd.ExecuteReader())
29. {
30. if (dr.Read())
31. {
32. using (MemoryStream ms = new MemoryStream(dr["picture"] as byte[]))
33. {
34. i = Image.FromStream(ms);
35. }
36. }
37. }
38. }
39. }
40. return i;
41.}
void SaveImage(Image i)
{
byte[] buffer = null;
using (MemoryStream ms = new MemoryStream())
{
i.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
buffer = ms.ToArray();
}
using (SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=test;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand("insert into tab1 values(@image)", con))
{
cmd.Parameters.Add(new SqlParameter("@image", buffer));
con.Open();
cmd.ExecuteNonQuery();
}
}
}
Image GetImage()
{
Image i = null;
using (SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=test;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand("select * from tab1", con))
{
con.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
if (dr.Read())
{
using (MemoryStream ms = new MemoryStream(dr["picture"] as byte[]))
{
i = Image.FromStream(ms);
}
}
}
}
}
return i;
}
Sql脚本:
01.use master
02.go
03.if exists(select * from sysdatabases where name='test')
04. drop database test
05.create database test
06.use test
07.go
08.create table tab1(picture image)
use master
go
if exists(select * from sysdatabases where name='test')
drop database test
create database test
use test
go
create table tab1(picture image)
运行效果:
源码下载地址:http://download.csdn.net/source/2877930 |