Code to save image in database

Virendradugar
Posted by Virendradugar under ASP.NET category on | Views : 4116
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

private byte[] ConvertImageToByteArray(System.Drawing.Image imageToConvert, System.Drawing.Imaging.ImageFormat formatOfImage)
{
byte[] Ret;
try
{
using (MemoryStream ms = new MemoryStream())
{
imageToConvert.Save(ms, formatOfImage);
Ret = ms.ToArray();
}
}
catch (Exception) { throw; }
return Ret;
}
protected void btnUpload_Click(object sender, EventArgs e)
{
System.Drawing.Image imag = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);
System.Data.SqlClient.SqlConnection conn = null;
try
{
try
{
conn = new System.Data.SqlClient.SqlConnection("[ConnectionString]");
conn.Open();
System.Data.SqlClient.SqlCommand insertCommand = new System.Data.SqlClient.SqlCommand("Insert into [tbl_Image] (ActualImage) Values (@Pic)", conn);
insertCommand.Parameters.Add("Pic", SqlDbType.Image, 0).Value = ConvertImageToByteArray(imag, System.Drawing.Imaging.ImageFormat.Jpeg);
int queryResult = insertCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
}
}
finally
{
if (conn != null)
conn.Close();
}

}
}


Kindly replace [ConnectionString] this with your own connection string.

Comments or Responses

Login to post response