Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save image in database using C# [closed]

I want to save user image into a database in C#. How do I do that?

like image 453
r.r Avatar asked Aug 23 '10 14:08

r.r


People also ask

Can We Save image in SQL database?

We can't store an image directly into the database. For this we have two solutions: To store the location of the image in the database. Converting the image into binary data and insert that binary data into database and convert that back to image while retrieving the records.

How do I store images in SQL database?

Insert one image into SQL Server This table will have an integer (int) id and the image column named img. The data type that we are going to use to store images is the varbinary(max). The INSERT statement inserts the value 1 as the id and then inserts the image named 1. png from the folder img in the c drive.


2 Answers

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 ();         }     } 
like image 73
jethro Avatar answered Sep 28 '22 04:09

jethro


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.

like image 45
Mike M. Avatar answered Sep 28 '22 04:09

Mike M.