将图片以二进制数组存入数据库,从数据库中取出转为图片

这篇博客介绍了如何将图片转换为二进制数组并存储到数据库中,以及如何从数据库中取出二进制数据,然后转换回图片。主要涉及文件流操作、SQL插入和查询,以及图片的保存和显示。

1. 将图片转为二进制存入数据库


      string road = Application.StartupPath;
            int index = road.LastIndexOf("bin");
            string roadsub = road.Substring(0, index);
            string roadNew = roadsub + "Resources\\Me.jpg";
            System.IO.FileStream fs = new System.IO.FileStream(roadNew, FileMode.OpenOrCreate,             FileAccess.Read);
            byte[] fileByte = new byte[fs.Length];
            fs.Read(fileByte, 0, (int)fs.Length);

            int j = -1;
            string sqlcommandText = @"insert into Picture (PContent)values(@pcontent)";
            j = SqlHelper.ExecuteNonQuery(sqlcommandText, new SqlParameter("@pcontent", SqlDbType.Image) { Value = fileByte});



2.将二进制取出,转为图片显示

            string road = Application.StartupPath;
            int index = road.LastIndexOf("bin");
            string roadsub = road.Substring(0, index);
            string roadNew = roadsub + "Resources\\" + userID + ".jpg";
            //对于展示头像先检测本地是否存在该照片
            if (File.Exists(roadNew) == true) 
            {
                //如果存在 ,直接将pictureBox路径指向该图片
                File.SetAttributes(roadNew, FileAttributes.Normal); //设置文件的属性为正常(如果文件为只读的话直接删除会报错)
                pictureBox1.Image = Image.FromFile(roadNew);
            }
            else //如果不存在,从数据库中读取头像二进制,并且生成头像,保存到Resource文件夹下,再将文件指向picktureBox
            {
                byte[] fileByte = employeeInfo.GeneratePicture(out messageHelper); 
                MemoryStream s = new MemoryStream(fileByte);
                Bitmap bt = new Bitmap(s);// stream你读取的流。
                bt.Save(roadNew, System.Drawing.Imaging.ImageFormat.Jpeg);// 保存为jpg。
            }    


       public byte[] GeneratePicture(out MessageHelper message)
        {
            byte[] fileByte = null;
            try
            {
                string sqlcommandText = @"select PContent from Picture where 1 = @userid";
                fileByte = (byte[])(SqlHelper.ExecuteScalar(sqlcommandText, new SqlParameter("@userid", SqlDbType.Int) { Value = 1 }));
                message = new MessageHelper() { messageCode = "0", messageText = "" };
            }
            catch(Exception ex)
            {
                message = new MessageHelper() { messageCode = "-1", messageText = "数据库连接失败: " + ex.Message.ToString() };
            }
            return fileByte;
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值