Visual C#: Retrieving Image (BLOB) from MySQL database
Posted: 14 Dec 2009, 15:48pm - Monday

I've been searching an article about storing and retrieving an image (BLOB data type) from MySQL database. Somehow, I only found the retrieving process but I created the storing process using PHP... :) You may download my works, link provided below...

  • idsystem_database.sql.zip - the dump file of MySQL database; import this SQL file before running the project
  • the rest of the files are the project sample files
-> [download id="5"] or http://blog.camilord.com/my.files/retrieveImg_public.zip For the credits, Thanks to Markusek Peter...
MySqlConnection myConnection = new MySqlConnection(myConnString); string testQuery = "SELECT sp.studePhoto, s.firstName, s.lastName FROM students AS s, student_photos AS sp WHERE s.id = sp.studentID"; MySqlCommand myCommand = new MySqlCommand(testQuery, myConnection); myConnection.Open(); MySqlDataReader myReader = myCommand.ExecuteReader(); FileStream fs; // Writes the BLOB to a file (*.jpg). BinaryWriter bw; // Streams the BLOB to the FileStream object. int bufferSize = 100; // Size of the BLOB buffer. // The BLOB byte[] buffer to be filled by GetBytes. byte[] outbyte = new byte[bufferSize]; long retval; // The bytes returned from GetBytes. long startIndex = 0; // The starting position in the BLOB output. while (myReader.Read()) { DateTime tmp = new DateTime(); tmp = DateTime.Now; // Create a file to hold the output. string filename = camilordMD5(tmp.ToLongDateString().ToString() + tmp.ToLongTimeString().ToString()) + ".jpg"; string dest = Directory.GetCurrentDirectory() + "/" + filename; fs = new FileStream(dest, FileMode.OpenOrCreate, FileAccess.Write); bw = new BinaryWriter(fs); // Reset the starting byte for the new BLOB. startIndex = 0; // Read the bytes into outbyte[] and retain the number of bytes returned. //myReader.GetBytes(0, startIndex, outbyte, 0, bufferSize); retval =(long) myReader.GetBytes(0, startIndex, outbyte, 0, bufferSize); lblName.Text = myReader.GetString(1) + " " + myReader.GetString(2); // Continue reading and writing while there are bytes beyond the size of the buffer. while (retval == bufferSize) { bw.Write(outbyte); bw.Flush(); // Reposition the start index to the end of the last buffer and fill thebuffer. startIndex += bufferSize; retval = myReader.GetBytes(0, startIndex, outbyte, 0, bufferSize); } pictureBox1.ImageLocation = Directory.GetCurrentDirectory() + "/test.jpg"; //pictureBox1.Image = retval; // Write the remaining buffer. bw.Write(outbyte, 0, (int)retval - 1); bw.Flush(); // Close the output file. bw.Close(); fs.Close(); }