Store Image in Database
private void button1_Click(object
sender, EventArgs
e)
{
System.Data.SqlClient.SqlConnection
cnn = new System.Data.SqlClient.SqlConnection();
cnn.ConnectionString=@"Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated
Security=True;User
Instance=True";
cnn.Open();
System.Data.SqlClient.SqlCommand
cmd = new System.Data.SqlClient.SqlCommand();
cmd.Connection = cnn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("Id",Convert.ToDecimal(textBox1.Text));
byte[] img;
Cls_Img clsimg=new Cls_Img();
// convert image to byte array using class
method
img=clsimg.Img2Byte(pictureBox1.Image);
cmd.Parameters.AddWithValue("Img",img);
cmd.CommandText = "Insert_Table1";
cmd.ExecuteNonQuery();
MessageBox.Show("Inset Completed");
}
class Cls_Img
{
public byte[]
Img2Byte(System.Drawing.Image
imagein)
{
System.IO.MemoryStream
ms = new System.IO.MemoryStream();
try
{
//Here We Use MemoryStream
Class To Write/Read Our Data
//Because MemoryStream
Class is Write Data On Memory(RAM)
//So we
Doesn't Need To Save a File Which Contain Binary Data on HardDrive.
imagein.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
}
catch (Exception)
{
}
//ms.ToArray Return
Byte Array
return ms.ToArray();
}
Retrieve Image From Database
private void button3_Click(object
sender, EventArgs
e)
{
System.Data.SqlClient.SqlConnection
cnn = new System.Data.SqlClient.SqlConnection();
System.Data.SqlClient.SqlCommand
cmd = new System.Data.SqlClient.SqlCommand();
System.Data.SqlClient.SqlDataAdapter
da = new System.Data.SqlClient.SqlDataAdapter();
System.Data.DataSet
ds = new DataSet();
System.Data.DataTable
dt = new DataTable();
cnn.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated
Security=True;User
Instance=True";
cnn.Open();
cmd.Connection = cnn;
cmd.CommandText = "Select
* from Table1 where id=" + Convert.ToDecimal(textBox1.Text);
da.SelectCommand
= cmd;
da.Fill(ds, "a");
dt = ds.Tables["a"];
Cls_Img clsimg = new Cls_Img();
byte[] x;
// get byte array from database
x = (byte[])dt.Rows[0][1];
// converting byte array to image using class
method
pictureBox2.Image = clsimg.byteArrayToImage(x);
}
public System.Drawing.Image byteArrayToImage(byte[] byteArrayIn)
{
System.IO.MemoryStream ms =
new System.IO.MemoryStream(byteArrayIn);
//Here We Use MemoryStream
Class To Write Image
// Input a BteArray
is Directly Convert in Image
// Using System.Drawing.Image.FromStream
// System.Drawing.Image.FromStream
Input Perameter is ByteArray
// System.Drawing.Image.FromStream
Output is System.Drawing.Image
System.Drawing.Image
returnImage = System.Drawing.Image.FromStream(ms);
// Return Image
return returnImage;
}
}