Home >Database >Mysql Tutorial >How Can I Store and Retrieve Images Using MySQL?
Using MySQL to Store and Retrieve Images
Saving an Image to the Database
To successfully save an image to a MySQL database, ensure that the following code is implemented:
<br>Dim filename As String = txtName.Text ".jpg"<br>Dim FileSize As UInt32</p> <p>conn.Close()</p> <p>Dim mstream As New System.IO.MemoryStream()<br>PbPicture.Image.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg)<br>Dim arrImage() As Byte = mstream.GetBuffer()</p> <p>FileSize = mstream.Length<br>Dim sqlcmd As New MySqlCommand<br>Dim sql As String<br>mstream.Close()</p> <p>sql = "insert into [your table] (picture, filename, filesize)</p> <pre class="brush:php;toolbar:false"> VALUES(@File, @FileName, @FileSize)"
Try
conn.Open() With sqlcmd .CommandText = sql .Connection = conn .Parameters.AddWithValue("@FileName", filename) .Parameters.AddWithValue("@FileSize", FileSize) .Parameters.AddWithValue("@File", arrImage) .ExecuteNonQuery() End With
Catch ex As Exception
MsgBox(ex.Message)
Finally
conn.Close()
End Try
Retrieving an Image from the Database
To display an image from the database in a PictureBox, use the following code:
<br>Dim adapter As New MySqlDataAdapter<br>adapter.SelectCommand = Cmd</p> <p>data = New DataTable</p> <p>adapter = New MySqlDataAdapter("select picture from [yourtable]", conn)</p> <p>commandbuild = New MySqlCommandBuilder(adapter)<br>adapter.Fill(data)</p> <p>Dim lb() As Byte = data.Rows(0).Item("picture")<br>Dim lstr As New System.IO.MemoryStream(lb)<br>PbPicture.Image = Image.FromStream(lstr)<br>PbPicture.SizeMode = PictureBoxSizeMode.StretchImage<br>lstr.Close()<br>
By implementing this code, you can store and retrieve images to and from a MySQL database successfully.
The above is the detailed content of How Can I Store and Retrieve Images Using MySQL?. For more information, please follow other related articles on the PHP Chinese website!