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

How to Store Images in a Database Using C#?

DDD
Release: 2024-12-30 22:43:10
Original
134 people have browsed it

How to Store Images in a Database Using C#?

Storing an Image in a Database Using C#

Seeking a solution to save user images in a C# database? This comprehensive guide will provide the steps and a ready-to-use method to accomplish this task.

Method Overview

The method outlined below leverages byte arrays to store the image data and utilizes IDataParameter to insert the binary data into the database.

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

public static void PersistImage(string path, IDbConnection connection)
{
    using (var command = connection.CreateCommand ())
    {
        Image img = Image.FromFile (path);
        MemoryStream tmpStream = new MemoryStream();
        img.Save (tmpStream, ImageFormat.Png); // modify to desired 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

Method Explanation

  1. Create a byte array (imgBytes) to store the image data.
  2. Obtain the image from the specified file path and save it to a memory stream (tmpStream).
  3. Reset the stream position and read the image bytes into the imgBytes array.
  4. Construct an SQL command to insert the image payload into the database.
  5. Create an IDataParameter named "payload" and set its properties to store binary data.
  6. Add the parameter to the SQL command and execute it to save the image.

By utilizing this robust method, developers can seamlessly persist images into their databases for further processing, storage, or retrieval.

The above is the detailed content of How to 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template