把图片保存到数据库中和从数据库中读取图片

最近做到一个小项目,其中关系到图片的一些操作。比如:将图片保存到数据库中、从数据库中读取图片、显示图片、打印图片等。此处对这些在项目中遇到的一些琐碎知识加以总结,以便日后查找。

 

  1、将图片作为其中的一个参数保存到数据库中

  在项目中,一般是将图片转换成二进制流格式,然后保存到数据库中。同时数据库表中存储图片的格式一般为image。此次项目,是将图片作为一个参数,和其他几个参数一起保存到数据库中,和在网上搜索到的图片保存不太一样,此处稍作修改,但都是检测过的。

  存储步骤:

  1、搜索到图片的路径

  2、读取图片并将图片转换成二进制流格式

  3、sql语句保存到数据库中。

   贴代码: 

private void btnWrite_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "*jpg|*.JPG|*.GIF|*.GIF|*.BMP|*.BMP";

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                string filePath = ofd.FileName;//图片路径
                FileStream fs = new FileStream(filePath, FileMode.Open);
                byte[] imageBytes = new byte[fs.Length];
                BinaryReader br = new BinaryReader(fs);
                imageBytes = br.ReadBytes(Convert.ToInt32(fs.Length));//图片转换成二进制流

                string strSql = string.Format("insert into [SBS].[dbo].[Model] ([M_QRCode],[M_Skills] ) values (@image,'2')");
                int count = Write(strSql,imageBytes );

                if (count > 0)
                {
                    MessageBox.Show("success");
                }
                else
                {
                    MessageBox.Show("failed");
                }
            }
        }
数据库连接和保存图片语句:
private int Write(string strSql,byte[] imageBytes)
        {
            string connStr = "Data Source=192.168.4.132;initial Catalog=SBS;User ID=sa;Password=sa;";

            using (SqlConnection conn = new SqlConnection(connStr))
            {
                using (SqlCommand cmd = new SqlCommand(strSql, conn))
                {
                    try
                    {
                        conn.Open();
                        SqlParameter sqlParameter = new SqlParameter("@image", SqlDbType.Image);
                        sqlParameter.Value = imageBytes;
                        cmd.Parameters.Add(sqlParameter);
                        int rows = cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (Exception e)
                    {
                        throw;
                    }
                }
            }
        }


 2、从数据库总读取图片

  从数据库中读取图片字段,并转换成内存流生成bitmap。

  贴代码: 

private void btnRead_Click(object sender, EventArgs e)
        {
            string strSql = string.Format("select M_QRCode from [SBS].[dbo].[Model] where M_id = 7");//图片保存的字段是M_QRCode
            Read(strSql);
        }

        private void Read(string strSql)
        {
            string connStr = "Data Source=192.168.4.132;initial Catalog=SBS;User ID=sa;Password=sa;";

            using (SqlConnection conn = new SqlConnection(connStr))
            {
                using (SqlCommand cmd = new SqlCommand(strSql, conn))
                {
                    conn.Open();
                    SqlDataReader sqlDr = cmd.ExecuteReader();
                    sqlDr.Read();
                    byte[] images = (byte[])sqlDr["M_QRCode"];
                    MemoryStream ms = new MemoryStream(images);
                    Bitmap bmp = new Bitmap(ms);
                    pictureBox1.Image = bmp;
                }
            }
        }

3、根据图片路径显示图片

  这个比较简单,直接贴出代码 

private void btnLoad_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "*jpg|*.JPG|*.GIF|*.GIF|*.BMP|*.BMP";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                pictureBox1.Image = Image.FromFile(ofd.FileName);
            }
        }

4、打印图片

  打印图片是在将图片显示在pictureBox的基础上进行的。

  步骤:

  1、将printDocument控件拖到界面,添加打印代码

  2、设置PrintDocument控件的Print_PrintPage事件

private void btnPrint_Click(object sender, EventArgs e)
        {
            PrintDialog printDialog = new PrintDialog();
            printDialog.Document = this.printDocument1;
            if (printDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    printDocument1.Print();
                }
                catch (Exception ex)
                {
                   printDocument1.PrintController.OnEndPrint(printDocument1, new System.Drawing.Printing.PrintEventArgs());
                }
            }
        }

        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            e.Graphics.DrawImage(pictureBox1.Image, 30, 30);
        }

 附带着将图片转换成二进制和将二进制转换成图片专门写出来,以便于查看。 

public byte[] ConvertBinary(string filePath)
        {
            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);//以文件流形式读取图片
            BinaryReader br = new BinaryReader(fs);//转换成二进制流
            byte[] imageBytes = br.ReadBytes((int)fs.Length);//保存到字节数组中

            return imageBytes;
        }

        public void ShowImage(byte[] imageBytes)
        {
            MemoryStream ms = new MemoryStream(imageBytes);
            pictureBox1.Image = Image.FromStream(ms);
        }

在pictureBox中显示图片的三种方式: 

public void Method()
        {
            MemoryStream ms;
            pictureBox1.Image = Image.FromStream(ms);

            Bitmap bitmap;
            pictureBox1.Image = bitmap;

            string filePath;
            pictureBox1.Image = Image.FromFile(filePath);
        }

winform中控件combobox控件使用: 

public void BindCombobox()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("id", typeof(int)));
            dt.Columns.Add(new DataColumn("value", typeof(string)));

            for (int i = 0; i < 3; i++)
            {
                DataRow dr = dt.NewRow();
                dr["id"] = i;
                dr["value"] = 10 + i;
                dt.Rows.Add(dr);
            }

            this.comboBox1.DataSource = dt;
            this.comboBox1.DisplayMember = "value";
            this.comboBox1.ValueMember = "id"; 
        }

        public void ShowValue()
        {
            this.textBox1.Text = this.comboBox1.Text;
            this.textBox2.Text = this.comboBox1.SelectedValue.ToString();
        }



  • 5
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值