How to save image in database using C#
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 ();
}
}
This is a method that uses a FileUpload control in asp.net:
byte[] buffer = new byte[fu.FileContent.Length];
Stream s = fu.FileContent;
s.Read(buffer, 0, buffer.Length);
//Then save 'buffer' to the varbinary column in your db where you want to store the image.
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.