Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert PictureBox to Sql Server Database Varbinary(MAX) with C#?

I have a table that have a field as Varbinary(MAX) datatype and I want to insert image file from PictureBox into this column. So how can I convert and insert image to Varbinary in Sql Server. Thank for help me.

like image 721
SOTHIK-Vicheachann Avatar asked Jun 03 '26 20:06

SOTHIK-Vicheachann


1 Answers

You should really show some code, what have you tried...

This is only a guess, but it should give you a clue how to insert picture into database:

//byte array that will hold image data
byte[] imageData = null;

using (var ms = new MemoryStream())
{
    //here is image property of your pictureBox control  saved into memory stream
    pictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
    imageData = ms.ToArray();
}

//make sql connection
SqlConnection conn = new SqlConnection("your connection string goes here");
// command with parameter
SqlCommand cmd = new SqlCommand("insert into TableWithImages (imageData) values (@imageData);", conn);
//define param and pass byte array as value
cmd.Parameters.Add("@imageData", SqlDbType.VarBinary).Value = imageData;

//do insert
cmd.ExecuteNonQuery();
like image 165
Nino Avatar answered Jun 06 '26 09:06

Nino