有时候我们需要将图片存到数库中的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];
2RLe1c:m,TV0 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;
}
}
本文介绍了如何使用C#将图片存储到数据库的Image类型字段中,并提供了存储与读取图片的具体实现步骤。通过FileStream和MemoryStream操作图片数据,利用SqlCommand执行SQL命令。
555

被折叠的 条评论
为什么被折叠?



