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

来源:互联网 发布:js获取整个form的值 编辑:程序博客网 时间:2024/05/01 04:42

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

0 0
原创粉丝点击