Home >Database >Mysql Tutorial >How to Efficiently Store and Retrieve Images in a MySQL Database?
This article addresses the challenge of storing and retrieving images from a database. The initial code provided encountered issues, prompting a deeper examination and a successful resolution.
The code snippet demonstrates how to save an image from a PictureBox (PbPicture) to a MySQL database:
Dim filename As String = txtName.Text + ".jpg" Dim FileSize As UInt32 conn.Close() Dim mstream As New System.IO.MemoryStream() PbPicture.Image.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg) Dim arrImage() As Byte = mstream.GetBuffer() FileSize = mstream.Length Dim sqlcmd As New MySqlCommand Dim sql As String = "insert into [your table] (picture, filename, filesize) " & _ "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
To retrieve an image from the database and display it in a PictureBox (PbPicture), follow these steps:
Dim adapter As New MySqlDataAdapter adapter.SelectCommand = Cmd data = New DataTable adapter = New MySqlDataAdapter("select picture from [yourtable]", conn)
Note: Ensure the query returns only one record since only one PictureBox can display a single image at a time.
commandbuild = New MySqlCommandBuilder(adapter) adapter.Fill(data) Dim lb() As Byte = data.Rows(0).Item("picture") Dim lstr As New System.IO.MemoryStream(lb) PbPicture.Image = Image.FromStream(lstr) PbPicture.SizeMode = PictureBoxSizeMode.StretchImage lstr.Close()
The above is the detailed content of How to Efficiently Store and Retrieve Images in a MySQL Database?. For more information, please follow other related articles on the PHP Chinese website!