How to save image in database using C# [closed]
Solution 1:
Try this method. It should work when field when you want to store image is of type byte
.
First it creates byte[]
for image. Then it saves it to the DB using IDataParameter
of type binary
.
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 ();
}
}
Solution 2:
You'll want to convert the image to a byte[]
in C#, and then you'll have the database column as varbinary(MAX)
After that, it's just like saving any other data type.