Home > Database > Mysql Tutorial > How to Save Images in a Database using C#?

How to Save Images in a Database using C#?

Barbara Streisand
Release: 2025-01-03 00:48:39
Original
587 people have browsed it

How to Save Images in a Database using C#?

Saving Images in a Database using C#

When storing user images in a database, it's essential to convert them into a binary format compatible with database storage. In C#, you can achieve this through the following steps:

  1. Create a Byte Array for Image Data:
    Convert the user image into a byte array. This step involves reading the image file using the File or Image class and saving it as a byte array.
  2. Use Parameterized Query with Binary Data:
    To prevent SQL injection attacks and improve performance, use a parameterized query with a parameter of type DbType.Binary. This parameter will hold the byte array representing the image data.
  3. Execute the Query to Save the Image:
    Execute the parameterized query to insert the image data into the database. The binary data will be stored in the specified column, preserving the image information.

Example Code:

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

public static void SaveImage(string path, IDbConnection connection)
{
    using (var command = connection.CreateCommand())
    {
        // Read the image file and convert it to a byte array
        Image img = Image.FromFile(path);
        MemoryStream tmpStream = new MemoryStream();
        img.Save(tmpStream, ImageFormat.Png);
        tmpStream.Seek(0, SeekOrigin.Begin);
        byte[] imgBytes = new byte[MAX_IMG_SIZE];
        tmpStream.Read(imgBytes, 0, MAX_IMG_SIZE);

        // Create a binary parameter for the image data
        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);

        // Execute the query to save the image
        command.ExecuteNonQuery();
    }
}
Copy after login

This code demonstrates how to convert an image into a byte array, create a binary parameter, and execute a parameterized query to store the image data in a database using C#.

The above is the detailed content of How to Save 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