1. Database named demo, data structure
2. Background code is as follows
classProgram { Public Static ReadOnly stringConstr ="Data Source =.; I Nitial Catalog = demo;integrated Security = SSPI;"; Static voidMain (string[] args) { #regionImage to binary stream write into databasebyte[] buffer = Imagetobyte (@"G:\2.jpg"); if(pushdatabase (buffer) >0) {Console.WriteLine ("OK"); Console.read (); } #endregion #regionBinary flow Picture//byte[] Gbuffer = getdatabase (3); //bytetoimage (Gbuffer); //Console.WriteLine ("OK"); //Console.read (); #endregion } /// <summary> ///picture to binary stream/// </summary> /// <param name= "Imgpath" >Picture Path</param> /// <returns></returns> Public Static byte[] Imagetobyte (stringImgpath) {Image Image=Image.FromFile (Imgpath); using(MemoryStream ms =NewMemoryStream ()) {image. Save (MS, image. Rawformat); byte[] buffer =New byte[Ms. Length]; Ms. Seek (0, Seekorigin.begin); Ms. Read (Buffer,0, buffer. Length); returnbuffer; } } /// <summary> ///byte flow picture/// </summary> /// <param name= "buffer" >Picture Binary Stream</param> Public Static voidBytetoimage (byte[] buffer) {MemoryStream ms=NewMemoryStream (); Ms. Write (Buffer,0, buffer. Length); Image img=Image.fromstream (MS); stringFile ="Mypicture2"; if(IMG. Rawformat = =imageformat.jpeg) {file+=". jpg"; } Else if(IMG. Rawformat = =imageformat.png) {file+=". PNG"; } Else{file+=". jpg"; } file.writeallbytes (File, buffer); } /// <summary> ///write into the database/// </summary> /// <param name= "buffer" >Picture Binary Stream</param> /// <returns></returns> Public Static intPushdatabase (byte[] buffer) { using(SqlConnection conn =NewSqlConnection (CONSTR)) { using(SqlCommand com =NewSqlCommand ()) {com. Connection=Conn; Conn. Open (); Com.commandtext="INSERT into ImageData values (@image)"; Com. Parameters.Add ("@image", Sqldbtype.image). Value =buffer; returncom. ExecuteNonQuery (); } } } /// <summary> ///reading from the database/// </summary> /// <returns></returns> Public Static byte[] Getdatabase (intID) {using(SqlConnection conn =NewSqlConnection (CONSTR)) { using(SqlCommand com =NewSqlCommand ()) {com. Connection=Conn; Conn. Open (); Com.commandtext="Select Imagebyte from ImageData where [email protected]"; Com. Parameters.Add ("@id", SqlDbType.Int). Value =ID; using(SqlDataReader reader =com. ExecuteReader ()) {if(reader. Read ()) {return(byte[]) reader[0]; } } } } return NULL; } }
Picture-to-binary stream stored in the database