Home > Database > Mysql Tutorial > body text

How to Store and Retrieve Images in a Database for PictureBox Display?

Barbara Streisand
Release: 2024-11-21 08:44:12
Original
395 people have browsed it

How to Store and Retrieve Images in a Database for PictureBox Display?

Image Storage and Retrieval for Picturebox Using Database Blob

Overview

This article addresses the issue of storing images as blobs in a database and retrieving them to display in a Picturebox control.

Inserting Image Data into Database

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()
Copy after login

Retrieving Image Data from Database

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()
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template