Home > Database > Mysql Tutorial > body text

How to Load and Display Images from a MySQL Database in C#?

Barbara Streisand
Release: 2024-10-30 07:37:03
Original
518 people have browsed it

How to Load and Display Images from a MySQL Database in C#?

How to Retrieve and Display Images from MySQL Database

Retrieving images from a MySQL database into a PictureBox control requires a specific approach with proper byte array handling. The following steps demonstrate the process:

Insert Image into MySQL Database

  1. Use the MySql.Data.MySqlClient library for MySQL database connectivity.
  2. Convert the image from file into a byte array: byte[] bytes = File.ReadAllBytes(ofd.FileName);
  3. Create a MySqlCommand and insert the byte array into the database using a parameter:

    cmd.Parameters.AddWithValue("@image", bytes);
    cmd.ExecuteNonQuery();
    Copy after login

Retrieve Image from MySQL Database

  1. A byte[] array is used to store the retrieved image: byte[] ImageByte = new byte[0];
  2. Execute a query with a parameter to retrieve the image:

    cmd.Parameters.AddWithValue("@id", Properties.Settings.Default.idImg);
    MySqlDataReader row;
    row = cmd.ExecuteReader();
    Copy after login
  3. Read the image byte array from the row:

    while (row.Read())
    {
     ImageByte = (Byte[])(row["image"]); 
    }
    Copy after login

Convert Byte Array to Image and Display

  1. Convert the byte array to an Image using the Helper.ByteArrayToImage method:

    roundPictureBox1.Image = byteArrayToImage(ImageByte);
    roundPictureBox1.Refresh();
    Copy after login

Enhancements

  • Consider using image optimization techniques to ensure images do not result in excessive file sizes.
  • Store the original file name in the database for easier retrieval and management outside the database.

The above is the detailed content of How to Load and Display Images from a MySQL Database in C#?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!