C # SQL Server database image access
# Region database image access //////Import images to the database//////Public void Import (string filePath) {string fileName = filePath. substring (filePath. lastIndexOf (@) + 1, filePath. lastIndexOf (.) -filePath. lastIndexOf (@)-1); FileStream fileStream = new FileStream (filePath, FileMode. open); byte [] imageBytes = new byte [fileStream. length]; BinaryReader binaryReader = new BinaryReader (fileStream); imageBytes = binaryReader. readBytes (Convert. toInt32 (fileStream. length); SqlConnection sqlConnection = new SqlConnection (@ data source = PANLEE-PCMSSQLSERVER_2; initial catalog = DBImage; integrated security = true); sqlConnection. open (); SqlCommand sqlCommand = new SqlCommand (); sqlCommand. connection = sqlConnection; try {string sqlCreate = @ Create Table Portraits (student ID varchar (50), photo image,); sqlCommand. commandText = sqlCreate; sqlCommand. executeNonQuery ();} catch {} sqlCommand. commandText = insert into Portraits (student ID, photo) values (@ ID, @ Image); sqlCommand. parameters. add (Image, SqlDbType. image); sqlCommand. parameters. add (ID, SqlDbType. varChar); sqlCommand. parameters [ID]. value = fileName; sqlCommand. parameters [Image]. value = imageBytes; sqlCommand. executeNonQuery (); sqlConnection. close ();}//////Export Images/////////
Bitmap
Public Bitmap Export (string SID) {byte [] imagebytes = null; SqlConnection sqlConnection = new SqlConnection (@ data source = PANLEE-PCMSSQLSERVER_2; initial catalog = DBImage; integrated security = true); sqlConnection. open (); SqlCommand sqlCommand = new SqlCommand (select photo from Portraits where student ID = @ ID, sqlConnection); sqlCommand. parameters. add (ID, SqlDbType. varChar); sqlCommand. parameters [ID]. value = SID; SqlDataReader sqlDataReader = sqlCommand. executeReader (); while (sqlDataReader. read () {imagebytes = (byte []) sqlDataReader. getValue (0);} sqlDataReader. close (); sqlCommand. clone (); sqlConnection. close (); MemoryStream MS = new MemoryStream (imagebytes); Bitmap bitmap = new Bitmap (MS); return bitmap;} # endregion