Linq实现图片数据存储在数据库中

本文介绍了一种在ASP.NET Web应用程序中使用C#语言进行数据库图片读取与写入的方法。通过具体的代码示例展示了如何从数据库中获取图片并显示在网页上,以及如何将图片文件保存到数据库中。该过程涉及到了文件流的操作、图片数据的转换等关键技术点。

数据库表定义:

image

代码实现:

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);
        }

转载于:https://www.cnblogs.com/liaofeifan/archive/2009/08/09/1542415.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值