In DB
create table test
(
Photoid varchar(10),
Photo Image
)
To Select A Image and preview it in picturebox
private void btnImgBrowse_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = new Bitmap(ofd.FileName);
textBox1.Text = ofd.FileName;
}
}
To Save In DB
private void btnSave_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection("Data Source=Server;Initial Catalog=Test;Integrated Security=True");
try
{
byte[] image = null;
FileStream fs = new FileStream(textBox1.Text, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
image = br.ReadBytes((int)fs.Length);
cn.Open();
string query = "insert into images (photoid,photo)values('" + textBox2.Text + "',@img)";
SqlCommand objcmd = new SqlCommand(query, cn);
objcmd.Parameters.Add(new SqlParameter("@img", image));
int rowaffected = objcmd.ExecuteNonQuery();
MessageBox.Show("Inserted Successfully");
MessageBox.Show(rowaffected + "row'(s)" + "affected");
cn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
To Show Image Back In PictureBox
private void btnShowImage_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection("Data Source=Server;Initial Catalog=Test;Integrated Security=True");
cn.Open();
SqlCommand cmd = new SqlCommand("select photo from images where photoid="+textBox2.Text,cn);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
byte[] img = (byte[])dr[0];
MemoryStream ms = new MemoryStream(img);
pictureBox1.Image = Image.FromStream(ms);
}
cn.Close();
}