Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image Save and Retrieve in SQL Server in asp.net using c#

I am trying to save images in a SQL Server database.

I convert the image to bytes and store in SQL Server, but now I want to convert the saved bytes to an image and show it on a label in asp.net using c#.

I tried a lot but didn't find a solution.

Here is the code (convert bytes to Image)

if (fImage.HasFile)
{
    if (fImage.PostedFile.ContentType == "image/jpg" || fImage.PostedFile.ContentType == "image/jpeg" || fImage.PostedFile.ContentType == "image/png")
    {
       int filelenght = fImage.PostedFile.ContentLength;
       byte[] imagebytes = new  byte[filelenght];
       fImage.PostedFile.InputStream.Read(imagebytes, 0, filelenght);
       SqlCommand cmd = new SqlCommand();
       cmd.CommandText = "Insert into tbImage(Img) values(@img)";
       cmd.Connection = con;
       cmd.Parameters.AddWithValue("@img", imagebytes);
       con.Open();
       cmd.ExecuteNonQuery();
       con.Close();
       Response.Write("Image saved to database");
    }
}
like image 720
Sahil Verma Avatar asked May 30 '26 20:05

Sahil Verma


1 Answers

Something like this will convert Byte[] to Image:

MemoryStream ms = new MemoryStream(byte);
Image i = Image.FromStream(ms);
like image 51
Wahtever Avatar answered Jun 02 '26 08:06

Wahtever



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!