Save image in image type datatype:
This is the sample code for save image in image type datatype in mssql table using csharp.
Code for create database
CREATE TABLE Images(
ImageID INT IDENTITY(1,1) PRIMARY KEY,
ImageData IMAGE)
In C# code behind: ImageID INT IDENTITY(1,1) PRIMARY KEY,
ImageData IMAGE)
protected void btnSaveImage_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
byte[] ImageData = ReadImage(FileUpload1.PostedFile.FileName);
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlcon"].ToString());
string query = "INSERT INTO Images VALUES(@ImageData)";
SqlCommand com = new SqlCommand(query, con);
com.Parameters.AddWithValue("@ImageData", (object)ImageData);
con.Open();
com.ExecuteNonQuery();
con.Close();
}
}
byte[] ReadImage(string ImagePath)
{
byte[] ImageData = null;
FileInfo fi = new FileInfo(ImagePath);
long NumberOfBytes = fi.Length;
FileStream fs = new FileStream(ImagePath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
ImageData = br.ReadBytes((int)NumberOfBytes);
return ImageData;
}
{
if (FileUpload1.HasFile)
{
byte[] ImageData = ReadImage(FileUpload1.PostedFile.FileName);
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlcon"].ToString());
string query = "INSERT INTO Images VALUES(@ImageData)";
SqlCommand com = new SqlCommand(query, con);
com.Parameters.AddWithValue("@ImageData", (object)ImageData);
con.Open();
com.ExecuteNonQuery();
con.Close();
}
}
byte[] ReadImage(string ImagePath)
{
byte[] ImageData = null;
FileInfo fi = new FileInfo(ImagePath);
long NumberOfBytes = fi.Length;
FileStream fs = new FileStream(ImagePath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
ImageData = br.ReadBytes((int)NumberOfBytes);
return ImageData;
}
Nice post very helpful
DBAKings