zoukankan      html  css  js  c++  java
  • 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();
            }

  • 相关阅读:
    进程二
    高德地图api的使用
    《架构即未来》读后感3
    三周总结
    性能战术:
    二周总结
    《 架构即未来》读后感2
    一周总结
    《架构即未来》读后感
    学生信息系统dao层
  • 原文地址:https://www.cnblogs.com/csMapx/p/2200819.html
Copyright © 2011-2022 走看看