The following articles mainly introduce the actual operation process of saving jpg images in MySQL. We all know that images in MySQL databases can be saved through blob, mediumbolb, and ongblob. of course, the operations of different image files may be different, such as. BMP.
Sample Code:
Save the image to MySQL
- private void btnOpenFile_Click(object sender, EventArgs e)
- {
Open an image file
- this.openFileDialog1.InitialDirectory = "C:\\";
- this.openFileDialog1.FileName = "";
- this.openFileDialog1.ShowDialog();
Connection string
- string connStr = "server=vitus;User Id=root;Password=******;Persist Security Info=True;database=Test";
- string sql = string.Format("insert into ImageTest values(@id,@picture)");
- FileStream fs = new FileStream(this.openFileDialog1.FileName,FileMode.Open);
- Byte[] bts = new Byte[fs.Length-1];
- fs.Read(bts,0,(int)fs.Length-1);
- MySqlConnection sqlConn = new MySqlConnection(connStr);
- MySqlCommand sqlComm = new MySqlCommand(sql,sqlConn);
- sqlComm.Parameters.Add("@id", MySqlDbType.Int32, 1);
- sqlComm.Parameters["@id"].Value = 2;
- sqlComm.Parameters.AddWithValue("@picture", bts);
- sqlConn.Open();
- sqlComm.ExecuteNonQuery();
- sqlConn.Clone();
- }
Read and display images from MySQL
- private void btnImageView_Click(object sender, EventArgs e)
- {
- string connStr = "server=vitus;User Id=root;Password=******;Persist Security Info=True;database=Test";
- string sql = string.Format("select * from ImageTest where id=2");
- MySqlConnection sqlConn = new MySqlConnection(connStr);
- MySqlCommand sqlComm = new MySqlCommand(sql, sqlConn);
- sqlConn.Open();
- MySqlDataReader dr = sqlComm.ExecuteReader(CommandBehavior.CloseConnection);
- Image image = null;
- while (dr.Read())
- {
- MemoryStream buff = new MemoryStream((byte[])dr[1]);
- image = Image.FromStream(buff, true);
- buff.Close();
- }
- this.pictureBox1.Image = image;
- }
The above content is an introduction to saving JPG images in MySQL. I hope you will find some gains.