This example describes how to save images to a database. To store images to the database, you must first create a table in the database, set the field type of the stored images to the image type, and use the filestream class and binaryreader to read the images in bytes, assign a byte array, and then use ADO. executenonquery () method of the sqlcommand object to save data to the database. The main code is as follows:
Private void button#click (Object sender, eventargs E)
{
Openfiledialog1.filter = "* JPG | *. jpg | *. gif | *. gif | *. BMP | *. BMP ";
If (openfiledialog1.showdialog () = dialogresult. OK)
{
String fullpath = openfiledialog1.filename; // file path
Filestream FS = new filestream (fullpath, filemode. Open );
Byte [] imagebytes = new byte [fs. Length];
Binaryreader BR = new binaryreader (FS );
Imagebytes = Br. readbytes (convert. toint32 (FS. Length ));
// Open the database
Sqlconnection con = new sqlconnection ("Server = (local); uid = sa; Pwd =; database = db_05 ");
Con. open ();
Sqlcommand COM = new sqlcommand ("insert into tb_08 values (@ imagelist)", con );
Com. Parameters. Add ("imagelist", sqldbtype. Image );
Com. Parameters ["imagelist"]. value = imagebytes;
Com. executenonquery ();
Con. Close ();
}
}
This example describes how to read images from a database. This example uses sqldatareader to read the image field value from the database, assign it to a byte [] byte array, and then read the image using the memorystream class and bitmap. The main code is as follows:
Private void button#click (Object sender, eventargs E)
{
Byte [] imagebytes = NULL;
// Open the database
Sqlconnection con = new sqlconnection ("Server = (local); uid = sa; Pwd =; database = db_05 ");
Con. open ();
Sqlcommand COM = new sqlcommand ("select top 1 * From tb_09", con );
Sqldatareader DR = com. executereader ();
While (dr. Read ())
{
Imagebytes = (byte []) DR. getvalue (1 );
}
Dr. Close ();
Com. Clone ();
Con. Close ();
Memorystream MS = new memorystream (imagebytes );
Bitmap BMP = new Bitmap (MS );
Picturebox1.image = BMP;
}
This example describes how to allow only the specified image format. To open an image file using the openfiledialog control, you only need to specify the filter attribute of the openfiledialog control as a specific image format. For example, to open the image of the. BMP file, the main code is as follows:
This. openfiledialog1.filter = "BMP file (*. BMP) | *. BMP ";
When you use the picturebox control to input an image, to unify the image size, you only need to set the sizemode attribute value of the control to stretchimage. The stretchimage value indicates that the image size will be adjusted to the size of the control. In this way, the image size is unified.