C# 利用datatable将sqlserver中的Image取出来

来源:互联网 发布:中世纪2原版优化9百科 编辑:程序博客网 时间:2024/04/30 04:20

               

先把sqlserver数据库一个表装载到datatable里面,然后进行如下操作

               Bitmap IMG!=null;

                Bitmap IMG2=null;

                MemoryStream ms=null;

                 byte[] b1 = (byte[])dt.Rows[0]["照片1"]; 
                 byte[] b2 = (byte[])dt.Rows[0]["照片2"]; 
                 ms = new MemoryStream(b1);
                IMG1 = new Bitmap(ms);//取出照片1
                 ms = new MemoryStream(b2);
               IMG2= new Bitmap(ms);//取出照片2
                ms.Flush();

                ms.Close();


网上还有好的办法。例如

存:

publicvoid Save()

{

using(System.IO.FileStream stream=new System.IO.FileStreamfile,System.IO.FileMode.Open,System.IO.FileAccess.Read)

{
byte[] buffer=newbyte[stream.Length];
stream.Read(buffer,
0, (int)stream.Length);
stream.Close();
string strName= System.IO.Path.GetFileNameWithoutExtension(file);
SqlCommand cmd
=new SqlCommand("Insert into Temp(name,photo) values(@name,@image)", sqlConn);
cmd.Parameters.Add(
"@name", SqlDbType.VarChar).Value= strName;
cmd.Parameters.Add(
"@image", SqlDbType.Image).Value= buffer;
cmd.ExecuteNonQuery();

}

}

取:

publicvoid GetImage()

{

SqlCommand cmd
=new SqlCommand(@"SELECT name, photo FROM Temp", sqlConn);
sqlConn.Open();
SqlDataReader reader
= cmd .ExecuteReader();
if (reader.Read())
{
image_filename
= (string) reader.GetValue(0);
byte[] image_bytes= (byte[]) reader.GetValue(1);
MemoryStream ms
=new MemoryStream(image_bytes);
Bitmap bmap
=new Bitmap(ms);
return
bmap;

}

}

阅读全文
0 0
原创粉丝点击