MSSQL Image 的存储与读取显示

1. 创建测试用数据表:
create table Test([ImageID] [int] IDENTITY (1, 1) NOT NULL , bmp Image)

2. 存储图像文件到数据库中:
            // SqlConnection 连接部分略
            string sqlStr = String.Format("insert into Test(bmp) values(@i)", comboBox1.Text);
            if (conn.State == ConnectionState.Closed)
                conn.Open();
            if (conn.State == ConnectionState.Open)
            {
                SqlCommand cmd = new SqlCommand(sqlStr, conn);
                FileStream stream = new FileStream("1.png", FileMode.Open);
                int len = (int)stream.Length;
                byte[] bytes = new byte[len];
                stream.Read(bytes, 0, len);
                cmd.Parameters.Add("@i", SqlDbType.Image, len);
                cmd.Parameters["@i"].Value = bytes;
                cmd.ExecuteNonQuery();
               
                stream.Close();
            }
            else
            {
                MessageBox.Show("打开数据库连接失败.");
            }
            conn.Close();

3. 从数据库中读取Image,并显示到PictureBox中:       

        BindingSource source = new BindingSource();

        source.PositionChanged += new EventHandler(source_PositionChanged);

        // 窗体上创建一个 BindingNavigator 数据导航控件, 当打开数据表后并在数据项之间移动时,触发如下事件方法:
        void source_PositionChanged(object sender, EventArgs e)
        {
            byte[] image_bytes = (byte[])((DataRowView)source.Current).Row["bmp"];
            MemoryStream stream = new MemoryStream(image_bytes);
            pictureBox1.Image = Image.FromStream(stream);
            stream.Close();
        }

你可能感兴趣的:(image)