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