"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Load and Display Images from a MySQL Database in C#?

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

Published on 2024-11-08
Browse:596

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();

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();
  3. Read the image byte array from the row:

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

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();

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.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3