• 基于winform的二进制图片数据的存取(用于数据库照片的读写处理)


    编程目的文本框1中输入id号,则从openFileDialog中选择的图片会以二进制数据存进SQL数据库的对应表的id列;文本框2中输入姓名,从数据库读取对应name的照片并显示在pictureBox控件上。

    预备操作新建一个sql数据库,包含一个拥有id和name,image的表,如下图所示,窗体中拖拽两个文本框和两个button按钮。


    1、主功能类

     

      public void SaveImage(string ID,OpenFileDialog openF)  //openFileDialog打开的图片以二进制流的方式存到数据库的指定表的指定id号的记录中
            { 
                string P_str = openF.FileName;
                FileStream fs = new FileStream(P_str,FileMode.Open,FileAccess.Read);
                BinaryReader br = new BinaryReader(fs);
                byte[] imageBytesIn = br.ReadBytes((int)fs.Length);
                SqlConnection conn = BaseClass.DBConn.CyCon();
                conn.Open();
                StringBuilder strSql = new StringBuilder();
                strSql.Append("update test_photo set photo=@Photo where id="+ID);
                SqlCommand cmd = new SqlCommand(strSql.ToString(),conn);
                cmd.Parameters.Add("@Photo",SqlDbType.Binary).Value=imageBytesIn;
                cmd.ExecuteNonQuery();
                conn.Close();
            }
    
            public void Get_Image(string  yname,PictureBox pb)//从数据库中读取指定姓名的二进制数据图片并显示
            {   byte[]imagebytes=null;
                SqlConnection conn = BaseClass.DBConn.CyCon();
                conn.Open();
                SqlCommand com=new SqlCommand("select * from test_photo where name='"+yname+"'",conn);
                SqlDataReader dr=com.ExecuteReader();
                while(dr.Read())
                {imagebytes=(byte[])dr.GetValue(1);}
                dr.Close();
                conn.Close();
                MemoryStream ms=new MemoryStream(imagebytes);
                Bitmap bmpt = new Bitmap(ms);
                pb.Image = bmpt;
              
            }

    2、调用类

     

      bll b = new bll();
            
            private void btnSavePhotoToDB_Click(object sender, EventArgs e)
            {
                
                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    b.SaveImage(textBox1.Text, openFileDialog1);
                    
                }
                
                MessageBox.Show("存照片成功");//支持bmp,jpg,gif
            }
    
            private void btnShowPhotoFromDB_Click(object sender, EventArgs e)
            {
                b.Get_Image(textBox2.Text, pictureBox1);
            }


    3、运行效果图




  • 相关阅读:
    1722 最优乘车 1997年NOI全国竞赛
    tarjan算法详解
    codevs 原创抄袭题 5969 [AK]刻录光盘
    Kosaraju算法详解
    1722 最优乘车 未完成
    codevs原创抄袭题 5960 信使
    1405 奶牛的旅行
    android 管理Bitmap内存
    Dynamics CRM 2013 初体验(3):新增加的功能
    在android画面切换时设置跟随变动的小圆圈
  • 原文地址:https://www.cnblogs.com/riskyer/p/3333771.html
Copyright © 2020-2023  润新知