Save images to the database and read images from the database

Source: Internet
Author: User
Recently, we have implemented a small project, which involves some operations on images. For example, save images to the database, read images from the database, display images, and print images. This section summarizes some of the trivial knowledge encountered in the project for future search. 1. save the image to the project as a parameter. generally

Recently, we have implemented a small project, which involves some operations on images. For example, save images to the database, read images from the database, display images, and print images. This section summarizes some of the trivial knowledge encountered in the project for future search. 1. save the image to the database as a parameter in the project. generally

Recently, we have implemented a small project, which involves some operations on images. For example, save images to the database, read images from the database, display images, and print images. This section summarizes some of the trivial knowledge encountered in the project for future search.

 1. save the image to the database as a parameter.

In a project, the image is generally converted to a binary stream format and then saved to the database. At the same time, the format for storing images in database tables is generally image. This project uses images as a parameter and saves them to the database together with several other parameters. it is not the same as the images found on the Internet and is slightly modified here, but all of them have been detected.

Storage steps:

1. search for the image path

2. read the image and convert it into a binary stream format

3. save SQL statements to the database.

Code:

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; // The Image path 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); // convert the image to a binary stream 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 ");}}}

Database Connection and save image statement:

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. read images from the database

  Read Image fields from the database and convert them into memory streams to generate bitmap.

Code:

Private void btnRead_Click (object sender, EventArgs e) {string strSql = string. format ("select M_QRCode from [SBS]. [dbo]. [Model] where M_id = 7 "); // The saved image field is 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. display images based on the image path

This is relatively simple, and the code is directly pasted

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. print images

Print an image based on pictureBox.

Steps:

1. drag the printDocument control to the interface and add the print code.

2. set the Print_PrintPage event of the PrintDocument control.

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

  

It is accompanied by converting an image into a binary image and converting it into an image to facilitate viewing.

Public byte [] ConvertBinary (string filePath) {FileStream fs = new FileStream (filePath, FileMode. open, FileAccess. read); // Read the image as a file stream. BinaryReader br = new BinaryReader (fs); // Convert it to a binary stream byte [] imageBytes = br. readBytes (int) fs. length); // save to the byte array return imageBytes;} public void ShowImage (byte [] imageBytes) {MemoryStream MS = new MemoryStream (imageBytes); pictureBox1.Image = Image. fromStream (MS );}

Three ways to display images in pictureBox:

public void Method()        {            MemoryStream ms;            pictureBox1.Image = Image.FromStream(ms);            Bitmap bitmap;            pictureBox1.Image = bitmap;            string filePath;            pictureBox1.Image = Image.FromFile(filePath);        }

Use the combobox control in winform:

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

The above is a summary of some trivial things, which can be used as a learning task in the future.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.