图片转二进制保存到数据库

通过二进制数组与数据存取图片库
我们做项目经常会遇到处理图片的问题,我们需要把图片进行存取,方法是有很多的。例如我们在客户端把图片上传到客户端的文件夹里,然后把客户端文件路径保存到数据库中,但是这种方法是不提倡的,因为存储到客户端安全性不高而且占用太多客户端的内存会影响程序性能,而且客户端改动大往往会得不偿失;相对来说的第二种方法就是把图片文件保存到服务端,服务端变动小,而且安全性比较高,如果服务是在云上且不会影响客户端的运行速度和内存占用,通过客户端代码处理图片就更为顺畅了;第三种就是通过二进制把图片保存到数据库中了,大家都知道文件就是流的形式存在的,我们可以把流转换为二进制保存到数据库中,通过流与二进制之间进行相互转换实现流的存取;
那我就介绍一下第三种存取图片的方法吧,通过二进制存取数据;
1、 我们先在数据库中创建一张(测试)表,添加name,photo字段以及字段类型
在这里插入图片描述

2、 然后我们创建一个窗体应用程序,在窗体类下创建连接数据库了对象和变量

  #region 定义公共的类对象及变量
       SqlConnection sqlcon;       //声明数据库连接对象
        SqlDataAdapter sqlda;       //声明数据桥接器对象
        DataSet myds;               //声明数据集对象
       //定义数据库连接字符串
       string strCon = @"Data Source=DESKTOP-NHR419E\SA;
Initial Catalog=TEST;UserID=sa;Password=123";
        #endregion

3、 窗体和窗体控件代码

  #region Windows 窗体设计器生成的代码
        /// <summary>
        /// 设计器支持所需的方法 - 不要
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.label1 = new System.Windows.Forms.Label();
            this.pictureBox1 = new System.Windows.Forms.PictureBox();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
            this.button1 = new System.Windows.Forms.Button();
            this.dataGridView1 = new System.Windows.Forms.DataGridView();
            this.label2 = new System.Windows.Forms.Label();
            this.button2 = new System.Windows.Forms.Button();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
            this.SuspendLayout();
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(12, 13);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(65, 12);
            this.label1.TabIndex = 0;
            this.label1.Text = "用户名称:";
            // 
            // pictureBox1
            // 
            this.pictureBox1.Location = new System.Drawing.Point(77, 37);
            this.pictureBox1.Name = "pictureBox1";
            this.pictureBox1.Size = new System.Drawing.Size(91, 113);
            this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
            this.pictureBox1.TabIndex = 1;
            this.pictureBox1.TabStop = false;
            // 
            // textBox1
            // 
            this.textBox1.Location = new System.Drawing.Point(77, 10);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(125, 21);
            this.textBox1.TabIndex = 2;
            // 
            // openFileDialog1
            // 
            this.openFileDialog1.FileName = "openFileDialog1";
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(174, 44);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(28, 93);
            this.button1.TabIndex = 3;
            this.button1.Text = "选择";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // dataGridView1
            // 
            this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dataGridView1.Location = new System.Drawing.Point(218, 10);
            this.dataGridView1.Name = "dataGridView1";
            this.dataGridView1.RowTemplate.Height = 23;
            this.dataGridView1.Size = new System.Drawing.Size(160, 140);
            this.dataGridView1.TabIndex = 4;
            this.dataGridView1.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellClick);
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(12, 44);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(65, 12);
            this.label2.TabIndex = 5;
            this.label2.Text = "用户头像:";
            // 
            // button2
            // 
            this.button2.Location = new System.Drawing.Point(85, 156);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(75, 23);
            this.button2.TabIndex = 6;
            this.button2.Text = "添加";
            this.button2.UseVisualStyleBackColor = true;
            this.button2.Click += new System.EventHandler(this.button2_Click);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(385, 187);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.dataGridView1);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.pictureBox1);
            this.Controls.Add(this.label1);
            this.Name = "Form1";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "使用二进制存取用户头像";
            this.Load += new System.EventHandler(this.Form1_Load);
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();
        }
        #endregion
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.PictureBox pictureBox1;
        private System.Windows.Forms.TextBox textBox1;
        private System.Windows.Forms.OpenFileDialog openFileDialog1;
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.DataGridView dataGridView1;
        private System.Windows.Forms.Label label2;
private System.Windows.Forms.Button button2;
 
4、显示、存取全部代码,已经注释
public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        #region 定义公共的类对象及变量
        SqlConnection sqlcon;       //声明数据库连接对象
        SqlDataAdapter sqlda;       //声明数据桥接器对象
        DataSet myds;               //声明数据集对象
      //定义数据库连接字符串
        string strCon = @"Data Source=DESKTOP-NHR419E\SA;Initial Catalog=TEST;User ID=sa;Password=123";
        #endregion
        /// <summary>
        /// 窗体加载事件
        /// </summary>
        /// <param name="sender"></param>
       /// <param name="e"></param>
       private void Form1_Load(object sender, EventArgs e)
       {
           ShowInfo();     //显示用户信息
       }
       //选择按钮点击事件
       private void button1_Click(object sender, EventArgs e)
       {
           //定义可选择的头像类型
            openFileDialog1.Filter = "*.jpg,*jpeg,*.bmp,*.ico,*.png,*.tif,*.wmf|*.jpg;*jpeg;*.bmp;*.ico;*.png;*.tif;*.wmf";
         openFileDialog1.Title = "选择头像";
           //判断是否选择了头像
          if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                //显示选择的用户头像
                pictureBox1.Image = Image.FromFile(openFileDialog1.FileName);
            }
        }
        /// <summary>
        /// 用户数据表格点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
       private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //记录选择的用户名
            string strName = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
            if (strName != "")
            {
                //实例化数据库连接对象
                sqlcon = new SqlConnection(strCon);    
                //实例化数据桥接器对象 通过当前点击行的用户名称返回用户信息
                sqlda = new SqlDataAdapter("select * from tbltest6 where name='" + strName + "'", sqlcon);
                myds = new DataSet();    //实例化数据集对象
                sqlda.Fill(myds);       //填充数据集
                //显示用户名称
                textBox1.Text = myds.Tables[0].Rows[0][0].ToString();
                //使用数据库中存储的二进制头像实例化内存数据流
                MemoryStream MStream = new MemoryStream((byte[])myds.Tables[0].Rows[0][1]);
                pictureBox1.Image = Image.FromStream(MStream);  //显示用户头像
            }
        }
        //添加按钮点击事件
        private void button2_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.FileName != "" && textBox1.Text != "")
            {
                //添加用户信息
                if (AddInfo(textBox1.Text, openFileDialog1.FileName))
               {
                   MessageBox.Show("用户信息添加成功");
                }
            }
            ShowInfo();
        }
    #region 添加用户信息
        /// <summary>
        /// 添加用户信息
        /// </summary>
        /// <param name="strName">用户名称</param>
        /// <param name="strImage">选择的头像名称</param>
       /// <returns>执行成功,返回true</returns>
        private bool AddInfo(string strName, string strImage)
     {
       //实例化数据库对象 通过字符串信息连接数据库
         sqlcon = new SqlConnection(strCon);
           //创建文件流,将图片转换成流
          FileStream FStream = new FileStream(strImage, FileMode.Open, FileAccess.Read);
         //创建二进制读取 流,将流转换成二进制数组
         BinaryReader BReader = new BinaryReader(FStream);
           byte[] byteImage = BReader.ReadBytes((int)FStream.Length);
            //创建Sql命令 通过sql存储语句新增用户信息
         SqlCommand sqlcmd = new SqlCommand("insert into tbltest6(name,photo) values(@name,@photo)", sqlcon);
          //给存储语句传参、赋值、参数类型
           sqlcmd.Parameters.Add("@name", SqlDbType.VarChar, 50).Value = strName;
           sqlcmd.Parameters.Add("@photo", SqlDbType.Image).Value = byteImage;
            //打开数据库对象
            sqlcon.Open();
            //返回结果是否大于0
            sqlcmd.ExecuteNonQuery();
            //关闭sql连接
            sqlcon.Close();
            return true;
        }
        #endregion
        #region 在DataGridView中显示用户名称
        /// <summary>
        /// 在DataGridView中显示用户名称
        /// </summary>
        private void ShowInfo()
        {
            //实例化数据库对象 通过字符串信息连接数据库
            sqlcon = new SqlConnection(strCon);
            //实例化数据桥连接对象 查询指定的数据,
            sqlda = new SqlDataAdapter("select name as 用户名称 from tbltest6", sqlcon);
            //实例化数据集
            myds = new DataSet();
            //把查询结果返回给数据集
            sqlda.Fill(myds);
            //绑定窗体的页面数据表格
            dataGridView1.DataSource = myds.Tables[0];
        }
        #endregion
       }

4、 代码都在上面,我们首先得在数据库建一张表,图片的类型用image类型,在窗体这里我们通过把图片转换为流再将图片转换为二进制保存,图片就是通过流的形式进行操作,本质是二进制。这就是我对图片转二进制保存到数据库的一个理解,对这方面并不太理解,还请指教

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值