数据库存取图片二进制数据

取出数据

       SqlConnection conn = new SqlConnection(@"data source=.;uid=sa;pwd=yzj;database=_Test");
            conn.Open();
            SqlCommand cmd = new SqlCommand("select Img from Image", conn);
            SqlDataReader reader = cmd.ExecuteReader();
            reader.Read();
            while (reader.Read())
            {
                for (int i = 0; i < reader.FieldCount; i++)
                {
                    MemoryStream buf = new MemoryStream((byte[])reader[i]);
                    Image image = Image.FromStream(buf, true);

                    pictureBox1.Image =new Bitmap(image, 200, 100);//缩放
                    pictureBox2.Image = image;
                }
            }  

 存入数据

SqlConnection conn = new SqlConnection(@"data source=.;uid=sa;pwd=yzj;database=_Test");
            conn.Open();
            SqlCommand cmd = new SqlCommand("insert into Image values(@i)", conn);
            byte[] ib = new byte[1000000];
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "打开";
            ofd.Filter = "所有文件|*.*";  //这是设置扩展名。
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                FileStream fs = new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read);
                fs.Read(ib, 0, 60000);
                cmd.Parameters.Add("@i", SqlDbType.Image, (int)fs.Length);
                cmd.Parameters["@i"].Value = ib;
                cmd.ExecuteNonQuery();
                conn.Close();
                MessageBox.Show("保存成功");
            }

 

posted @ 2012-08-07 14:05  yzj1212  阅读(187)  评论(0编辑  收藏  举报