有时候我们需要将图片存到数库中的Imgae类型的字段下,以下是存取的两种方法:

存:

public void Save()

{

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

{
    byte[] buffer = new byte[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();

}

}

取:

public void 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;

}

}

posted on 2009-03-10 10:12  John.Lau  阅读(3939)  评论(0编辑  收藏  举报