把圖片保存到數據庫中和從數據庫中讀取圖片--項目瑣碎總結


  最近做到一個小項目,其中關系到圖片的一些操作。比如:將圖片保存到數據庫中、從數據庫中讀取圖片、顯示圖片、打印圖片等。此處對這些在項目中遇到的一些瑣碎知識加以總結,以便日后查找。

 

  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;
                    }
                }
            }
        }
View Code

 

  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();
        }

 

  以上就是一些瑣碎的總結,謹作為日后學習工作使用。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM