I want to save user image into a database in C#. How do I do that?
You'll need to serialize the image to a binary format that can be stored in a SQL BLOB column. Assuming you're using SQL Server, here is a good article on the subject:
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.
Hi,you can save the path of the image in the database or save the image itself as a BLOB ( binary - array of bytes)..it depends on the case you got,if your application is a web application,then saving the path of the image is much better.but if you got a client based application that connects to a centralized database,then you must save it as binary.
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.
Since you are using SQL, would recommend against using adhoc ('writing statements in strings'), especially given that you are loading an image.
ADO.NET can do all of the hard work of mapping, escaping etc for you.
Either create a Stored Procedure, or use SqlParameter to do the binding.
As the other posters say, use VARBINARY(MAX) as your storage type - IMAGE is being depracated.
Try this method. It should work when field when you want to store image is of type bytea
.
First it creates byte[]
for image. Then it saves it DB using IDataParameter
of type binary
.
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 ();
}
}
My personal preference is not to save the images to a database as such. Save the image somewhere in the file system and save a reference in the database.