图片存储与读取

存储图片

try
            {
                string strConn = "Server=.;DataBase=tempdb;Integrated Security=true";
                SqlConnection connection = new SqlConnection(strConn);
                string sql = "insert into Images (blobdata) values (@blobdata)";
                SqlCommand command = new SqlCommand(sql, connection);
                //图片路径
                string picturePath = @"D:/pic.jpg";  //注意,这里需要指定保存图片的绝对路径和图片 

                                               //文件的名称,每次必须更换图片的名称,这里很为不便
                //创建FileStream对象
                FileStream fs = new FileStream(picturePath, FileMode.Open, FileAccess.Read);
                //声明Byte数组
                Byte[] mybyte = new byte[fs.Length];
                //读取数据
                fs.Read(mybyte,0,mybyte.Length);
                fs.Close();
                //转换成二进制数据,并保存到数据库
                SqlParameter prm = new SqlParameter
("@blobdata",SqlDbType.VarBinary,mybyte.Length,ParameterDirection.Input,false,0,0,null,DataRowVersion.Current,mybyte);
                command.Parameters.Add(prm);
                //打开数据库连接
                connection.Open();
                command.ExecuteNonQuery();
                connection.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
       

读取图片
            try
            {
                //创建数据库连接字符串
                string strConn = "Server=.;DataBase=tempdb;Integrated Security=True";
                //创建SqlConnection对象
                SqlConnection connection = new SqlConnection(strConn);
                //打开数据库连接
                connection.Open();
                //创建SQL语句
                string sql = "select blodid,blobdata from Images order by blodid";
                //创建SqlCommand对象
                SqlCommand command = new SqlCommand(sql, connection);
                //创建DataAdapter对象
                SqlDataAdapter dataAdapter = new SqlDataAdapter(command);
                //创建DataSet对象
                DataSet dataSet = new DataSet();
                dataAdapter.Fill(dataSet, "BLOBTest");
                int c = dataSet.Tables["BLOBTest"].Rows.Count;
                if (c > 0)
                {
                    Byte[] mybyte = new byte[0];
                    mybyte = (Byte[])(dataSet.Tables["BLOBTest"].Rows[c - 1]["BLOBData"]);
                    MemoryStream ms = new MemoryStream(mybyte);
                    pictureBox1.Image = Image.FromStream(ms);
                }
                connection.Close();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值