Store images in the database as images. First, obtain the stream object of the image, and then use the read method to read binary data from the image file and store the data in byte arrays.
Read fields of the image type from the database. First, store the fields of the image type corresponding to the database in an unsigned direct array, then read the image data using the memorystream class, and generate a bitmap object using the memorystream object, displayed on the picturebox control. The Code is as follows:
Private void butopen_click (Object sender, eventargs E)
{
Openfiledialog of = new openfiledialog ();
Of. Filter = "image files (*. BMP; *. jpg; *. GIF) | *. BMP; *. jpg; *. GIF ";
Of. defaultext = "BMP ";
Of. showdialog ();
If (of. filename. length> 0)
{
Using (Stream sr = of. openfile ())
{
Int length = (INT) Sr. length;
Byte [] B = new byte [length];
Sr. Read (B, 0, length );
Picturebox1.image = new Bitmap (SR );
/// Save
Try
{
Using (sqlconnection con = new sqlconnection ("Server =.; uid = sa; Pwd = 123; database = db_13 "))
{
Sqldataadapter ap = new sqldataadapter ("select * From tb_48", con );
Sqlcommandbuilder cmd = new sqlcommandbuilder (AP );
AP. updatecommand = cmd. getupdatecommand ();
Dataset DS = new dataset ();
AP. Fill (DS );
Datarow newrow = Ds. Tables [0]. newrow ();
Newrow. beginedit ();
Newrow ["name"] = of. filename;
Newrow ["image"] = B;
Newrow. endedit ();
DS. Tables [0]. Rows. Add (newrow );
AP. Update (DS );
MessageBox. Show ("Save succesful ");
}
}
Catch (exception ex)
{
MessageBox. Show (ex. Message );
}
}
}
}
Private void butload_click (Object sender, eventargs E)
{
Try
{
Using (sqlconnection con = new sqlconnection ("Server =.; uid = sa; Pwd = 123; database = db_13 "))
{
Sqldataadapter ap = new sqldataadapter ("select top 1 * From tb_48 order by id desc", con );
Sqlcommandbuilder cmd = new sqlcommandbuilder (AP );
AP. updatecommand = cmd. getupdatecommand ();
Dataset DS = new dataset ();
AP. Fill (DS );
Byte [] B = (byte []) ds. Tables [0]. Rows [0] ["image"];
Using (memorystream sr = new memorystream (B ))
{
Picturebox1.image = new Bitmap (SR );
}
MessageBox. Show ("load succesful ");
}
}
Catch (exception ex)
{
MessageBox. Show (ex. Message );
}
}