关于sql2005从数据库存取图片

 private void button1_Click(object sender, EventArgs e)
        {
            FileStream fs = new FileStream(@"C:\Documents and Settings\Administrator\桌面\存放图片\C#电子像册\dzxc\dzxc\bin\Debug\Image\4.jpg", FileMode.Open, FileAccess.Read);//读取D盘c.jpg转换为数据流
            Byte[] btye2 = new byte[fs.Length];
            fs.Read(btye2, 0, Convert.ToInt32(fs.Length));
            fs.Close();

            using (SqlConnection conn = new SqlConnection("server=(local);uid=sa;pwd=123;database=teach"))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.CommandText = "insert into image(image) values(@image)";//插入数据库
                SqlParameter par = new SqlParameter("@image", SqlDbType.Image);
                par.Value = btye2;
                cmd.Parameters.Add(par);

                int t = (int)(cmd.ExecuteNonQuery());
                if (t > 0)
                {
                    MessageBox.Show("插入成功!");
                }
                conn.Close();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            byte[] MyData = new byte[0];
            using (SqlConnection conn = new SqlConnection("server=(local);uid=sa;pwd=123;database=teach"))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.CommandText = "select image from image where id='1'";
                SqlDataReader sdr = cmd.ExecuteReader();
                sdr.Read();
                MyData = (byte[])sdr["image"];//读取第一个图片的位流
                int ArraySize = MyData.GetUpperBound(0);//获得数据库中存储的位流数组的维度上限,用作读取流的上限
                MemoryStream ms = new MemoryStream(MyData,true);
                ms.Write(MyData,0,MyData.Length);
                pictureBox1.Image = new Bitmap(ms, true);
                conn.Close();
                MessageBox.Show("读取成功!");
            }
        }

你可能感兴趣的:(image,C#,存取图片,image类型)