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