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

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

Barbara Streisand
Barbara StreisandOriginal
2024-10-30 07:37:03519browse

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.

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!

Statement:
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