Home > Database > Mysql Tutorial > How Can I Store Images in a Database Using C#?

How Can I Store Images in a Database Using C#?

Susan Sarandon
Release: 2025-01-04 18:13:41
Original
410 people have browsed it

How Can I Store Images in a Database Using C#?

Using C# to Store Images in a Database

Storing user images in a database is a common task in web development. In C#, there are a few ways to approach this. One method involves converting the image into a byte array and saving it to a database field of type byte.

Solution:

To implement this approach, you can use the following method:

using System.Drawing;
using System.Drawing.Imaging;
using System.Data;

public static void PerisitImage(string path, IDbConnection connection)
{
    using (var command = connection.CreateCommand ())
    {
        Image img = Image.FromFile (path);
        MemoryStream tmpStream = new MemoryStream();
        img.Save (tmpStream, ImageFormat.Png); // change to other format
        tmpStream.Seek (0, SeekOrigin.Begin);
        byte[] imgBytes = new byte[MAX_IMG_SIZE];
        tmpStream.Read (imgBytes, 0, MAX_IMG_SIZE);

        command.CommandText = "INSERT INTO images(payload) VALUES (:payload)";
        IDataParameter par = command.CreateParameter();
        par.ParameterName = "payload";
        par.DbType = DbType.Binary;
        par.Value = imgBytes;
        command.Parameters.Add(par);
        command.ExecuteNonQuery ();
    }
}
Copy after login

In this method:

  1. The Image class is used to load the image from a file.
  2. A MemoryStream is used to store the image in memory.
  3. The Save method is used to write the image to the MemoryStream in PNG format.
  4. The Seek method is used to reset the position of the MemoryStream to the beginning.
  5. The Read method is used to read the image bytes into a byte array.
  6. An IDataParameter of type DbType.Binary is used to pass the byte array to the database.
  7. The CommandText is used to specify the SQL query to insert the image into the database.
  8. The ExecuteNonQuery method is used to execute the query.

The above is the detailed content of How Can I Store Images in a Database Using 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