将图片转换成二进制流,然后写入数库,很多人遇到输出的时候是 System.byte[]的情况。现在将实例承上。
插入数据图片
1
protected
void
btnup_Click(
object
sender, EventArgs e)
2 {
3 SqlConnection conn = new SqlConnection( " server=.;database=test;uid=sa;pwd=sa; " );
4 conn.Open();
5 string imgpath = file1.PostedFile.FileName.ToString();
6 string imgtype = Path.GetExtension(imgpath);
7 SqlCommand cmd = new SqlCommand( " insert into imgname (imgname) values (@img) " ,conn);
8 SqlParameter param = new SqlParameter( " @img " , SqlDbType.Image, int .MaxValue);
9 param.Value = getpic(imgpath);
10 cmd.Parameters.Add(param);
11 cmd.ExecuteNonQuery();
12 conn.Close();
13 }
2 {
3 SqlConnection conn = new SqlConnection( " server=.;database=test;uid=sa;pwd=sa; " );
4 conn.Open();
5 string imgpath = file1.PostedFile.FileName.ToString();
6 string imgtype = Path.GetExtension(imgpath);
7 SqlCommand cmd = new SqlCommand( " insert into imgname (imgname) values (@img) " ,conn);
8 SqlParameter param = new SqlParameter( " @img " , SqlDbType.Image, int .MaxValue);
9 param.Value = getpic(imgpath);
10 cmd.Parameters.Add(param);
11 cmd.ExecuteNonQuery();
12 conn.Close();
13 }
显示数据图片
1
protected
void
btnout_Click(
object
sender, EventArgs e)
2 {
3 DataSet ds = new DataSet();
4 SqlConnection conn = new SqlConnection( " server=.;database=test;uid=sa;pwd=sa; " );
5 SqlDataAdapter sap = new SqlDataAdapter( " select top 1 * from imgname order by ID desc " , conn);
6 sap.Fill(ds);
7 Response.Clear();
8 // Response.BinaryWrite((byte[])ds.Tables[0].Rows[0]["imgname"]);
9 Response.OutputStream.Write(( byte [])ds.Tables[ 0 ].Rows[ 0 ][ " imgname " ], 0 , (( byte [])ds.Tables[ 0 ].Rows[ 0 ][ " imgname " ]).Length);
10 }
2 {
3 DataSet ds = new DataSet();
4 SqlConnection conn = new SqlConnection( " server=.;database=test;uid=sa;pwd=sa; " );
5 SqlDataAdapter sap = new SqlDataAdapter( " select top 1 * from imgname order by ID desc " , conn);
6 sap.Fill(ds);
7 Response.Clear();
8 // Response.BinaryWrite((byte[])ds.Tables[0].Rows[0]["imgname"]);
9 Response.OutputStream.Write(( byte [])ds.Tables[ 0 ].Rows[ 0 ][ " imgname " ], 0 , (( byte [])ds.Tables[ 0 ].Rows[ 0 ][ " imgname " ]).Length);
10 }
图片转换
1
protected
byte
[] getpic(
string
imagepath)
2 {
3 MemoryStream ms = new MemoryStream();
4 FileStream fs = new FileStream(imagepath, FileMode.Open);
5 byte [] bydate = new byte [fs.Length];
6 fs.Read(bydate, 0 , bydate.Length);
7 fs.Close();
8 return bydate;
9 }
2 {
3 MemoryStream ms = new MemoryStream();
4 FileStream fs = new FileStream(imagepath, FileMode.Open);
5 byte [] bydate = new byte [fs.Length];
6 fs.Read(bydate, 0 , bydate.Length);
7 fs.Close();
8 return bydate;
9 }