Images to binary streams are stored in the database, binary Database
1. Database Name: Demo, Data Structure
2. The background code is as follows:
Class Program {public static readonly string conStr = "Data Source = .; initial Catalog = Demo; Integrated Security = SSPI; "; static void Main (string [] args) {# Write the region image into the database byte [] buffer = ImageToByte (@ "G: \ 2.jpg"); if (PushDataBase (buffer)> 0) {Console. writeLine ("OK"); Console. read () ;}# endregion # region binary stream image // byte [] gBuffer = GetDataBase (3); // ByteToImage (gBuffer); // Console. writeLine ("OK"); // Console. read (); # endregion} // <summary> // convert an image to a binary stream // </summary> // <param name = "imgPath"> image path </param> /// <returns> </returns> public static byte [] ImageToByte (string imgPath) {Image image = Image. fromFile (imgPath); using (MemoryStream MS = new MemoryStream () {image. save (MS, image. rawFormat); byte [] buffer = new byte [ms. length]; ms. seek (0, SeekOrigin. begin); ms. read (buffer, 0, buffer. length); return buffer ;}} /// <summary> // byte Transfer picture /// </summary> /// <param name = "buffer"> image binary stream </param> public static void byteToImage (byte [] buffer) {MemoryStream ms = new memorystreams (); ms. write (buffer, 0, buffer. length); Image img = Image. fromStream (MS); string file = "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 data to the database /// </summary> /// <param name = "buffer"> image binary stream </param> /// <returns> </returns> public static int PushDataBase (byte [] buffer) {using (SqlConnection conn = new SqlConnection (conStr) {using (SqlCommand com = new SqlCommand () {com. connection = conn; conn. open (); com. commandText = "insert into ImageData values (@ image)"; com. parameters. add ("@ image", SqlDbType. image ). value = buffer; return com. executeNonQuery ();}}} /// <summary> /// read from the database /// </summary> /// <returns> </returns> public static byte [] GetDataBase (int id) {using (SqlConnection conn = new SqlConnection (conStr) {using (SqlCommand com = new SqlCommand () {com. connection = conn; conn. open (); com. commandText = "select ImageByte from ImageData where Id = @ id"; com. parameters. add ("@ id", SqlDbType. int ). value = id; using (SqlDataReader reader = com. executeReader () {if (reader. read () {return (byte []) reader [0] ;}}} return null ;}}