/Asp tutorial. net how to save SQL server and display images
Private void form1_load (object sender, eventargs e)
{
Filestream fs = new filestream (@ "c: e06d3510ebfde555cb80c4de.jpg", filemode. open );
Int ilength = int. parse (fs. length. tostring (); // obtain the length of the current file.
Byte [] filebyte = new byte [ilength]; // creates an array of byte [] to save the file content
Fs. read (filebyte, 0, ilength); // read the object content to the byte [] array through the read method.
Fs. dispose ();
Sqlconnection conn = new sqlconnection (@ "server = localhost; integrated security = sspi; initial catalog = qq ");
// Insert database tutorial
String strsql = "insert into tbl_image (img) values (@ img )";
Sqlcommand cmd = new sqlcommand (strsql, conn );
Cmd. parameters. add ("@ img", sqldbtype. image, ilength). value = filebyte;
// The parameter value of the image saved by the value assignment, which is sqldbtype. binary
Conn. open (); // open the connection
Cmd.exe cutenonquery (); // execute the command
Conn. close ();
}
// Display images in the database
Private void button#click (object sender, eventargs e)
{
Byte [] filecontent;
Using (sqlconnection conn = new sqlconnection (@ "server = localhost; integrated security = sspi; initial catalog = qq "))
{
String strsql = "select img from tbl_image ";
Sqlcommand cmd = new sqlcommand (strsql, conn );
Conn. open ();
Sqldatareader dr = cmd.exe cutereader ();
// The preceding steps complete the execution of General sqlcommand commands,
// Returns a sqldatareader that assigns the image content to a byte [] array.
If (dr. read ())
{
Filecontent = (byte []) dr ["img"];
}
Else
{
Filecontent = new byte [0];
}
Dr. close ();
}
Memorystream MS = new memorystream (filecontent, 0, filecontent. length );
This. pbshowimage. image = image. fromstream (MS );
// Disable the memory stream
Ms. close ();
}