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 (); } }
Method Explanation
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!