This article addresses the issue of storing images as blobs in a database and retrieving them to display in a Picturebox control.
To store an image in a database, the first step is to convert it into a binary format. This can be achieved using the Save method with the appropriate ImageFormat parameter.
Here's an example of inserting image data into a database:
Dim filename As String = txtName.Text + ".jpg" Dim FileSize As UInt32 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 mstream.Close() sql = "insert into [your table] (picture, filename, filesize) VALUES(@File, @FileName, @FileSize)" conn.Open() With sqlcmd .CommandText = sql .Connection = conn .Parameters.AddWithValue("@FileName", filename) .Parameters.AddWithValue("@FileSize", FileSize) .Parameters.AddWithValue("@File", arrImage) .ExecuteNonQuery() End With conn.Close()
To retrieve an image from the database and display it in a Picturebox, follow these steps:
Dim adapter As New MySqlDataAdapter adapter.SelectCommand = Cmd data = New DataTable adapter = New MySqlDataAdapter("select picture from [yourtable]", conn) 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()
By implementing these methods, you can seamlessly store and retrieve images in and from a database for display in Picturebox controls.
The above is the detailed content of How to Store and Retrieve Images in a Database for PictureBox Display?. For more information, please follow other related articles on the PHP Chinese website!