//Save Image
SqlConnection cn = new SqlConnection("data source=localhost;initial catalog=notitest;user id=sa;password=cos123");
cn.Open();
SqlCommand cmd = new SqlCommand("insert imgtest values(" + textBox1.Text + ",'" + ImageToBase64(pictureBox1.Image,
System.Drawing.Imaging.ImageFormat.Png) + "')", cn);
SqlDataReader dr = cmd.ExecuteReader();
cn.Close();
//Retrive
SqlConnection cn = new SqlConnection("data source=localhost;initial catalog=notitest;user id=sa;password=cos123");
cn.Open();
SqlCommand cmd = new SqlCommand("select * from imgtest", cn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
textBox2.Text = dr[0].ToString();
pictureBox2.Image = Base64ToImage(dr[1].ToString());
}
cn.Close();
//Methods
public string ImageToBase64(Image image,
System.Drawing.Imaging.ImageFormat format)
{
using (MemoryStream ms = new MemoryStream())
{
image.Save(ms, format);
byte[] imageBytes = ms.ToArray();
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
public Image Base64ToImage(string base64String)
{
byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(imageBytes, 0,
imageBytes.Length);
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true);
return image;
}