Linq实现图片数据存储在数据库中
数据库表定义:
代码实现:
public partial class DBImageTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//GetRecord(1);
}
}
private void GetRecord(int id)
{
using (DCDataContext oDB = new DCDataContext())
{
Test item = oDB.Test.Single(c => c.id == id);
// item.image.ToArray();
if (item.image != null)
{
byte[] image = item.image.ToArray();
string temppath = Server.MapPath("/images/");
FileStream temp = new FileStream(temppath+"gg.jpg", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
temp.SetLength(image.Length);
temp.Write(image, 0, image.Length);
temp.Close();
}
}
}
private void WriteImage(int id)
{
using (DCDataContext oDB = new DCDataContext())
{
Test item = oDB.Test.Single(c => c.id == id);
string temppath = Server.MapPath("/images/");
FileStream temp = new FileStream("gg.jpg", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
byte[] image = new byte[temp.Length];
for (int i = 0; i < temp.Length; i++)
{
image[i] =(byte) temp.ReadByte();
}
Response.Write("写入前长度" + item.image.Length.ToString());
item.image = image;
Response.Write("写入后长度" + item.image.Length.ToString());
oDB.SubmitChanges();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
GetRecord(1);
Image1.ImageUrl = "/images/gg.jpg";
}
protected void Button2_Click(object sender, EventArgs e)
{
WriteImage(1);
}