Reply to Inserting modified image into a database

Inserting modified image into a database new!
by Rocket Dog, 16 years, 4 months ago
There are several posts on this forum from people struggling to insert a modified image into a database. At first I struggled with this as well, but then the light bulb went on and I discovered the solution. I'd like to share it with you now as a form of "payment" for the use of this class. I'm working on my Master's degree in Web Development Technologies at the moment, and this upload class has proven to be extremely useful and saved me a lot of work, so I figured this is the least I could do. (This solution assumes you are using PHP and MySQL, but the same concept applies if you are using a different language/database combination.)

In a nutshell, what you will need to do is to output your modified file to the server, then read it back using PHP. You could also remove the file from the server afterwards if desired, also using PHP (but this is not shown in my code example below). Here is what the code looks like:

include('class.upload.php');
$foo = new upload($_FILES['form_field']);
if ($foo->uploaded) {
  // Modify the image however you like.  For instance...
  $foo->image_convert         = 'jpg';
  $foo->image_resize           = true;
  $foo->image_x                  = 100;
  $foo->image_ratio_y          = true;
  $foo->file_new_name_body = 'image_resized';
  // Store the directory where you want to save the image.
  $directory = "./photos/";
  // Save the modified image to the desired directory on the server.
  $foo->process($directory);
  // File WAS processed successfully.
  if ($foo->processed) {
    // Store the name of the image that was just saved.
    $filename = $foo->file_dst_name;
    // Store the full path to the image.
    $path = $directory . $filename;
    // Using PHP functions, stream the image file data into a "$file" variable.
    // This is what you will later insert into your MySQL database as a BLOB!
    $temp  = fopen($path, 'r');
    $image = fread($temp, filesize($path));
    $file  = addslashes($image);
    fclose($temp);
    // Delete the temporary file(s).
    $foo->clean();
  }
  // File was NOT processed successfully.
  else {
    echo 'error : ' . $foo->error;
  }
// Build a MySQL query string using the "$file" variable into which you streamed the image data.
$query = " INSERT INTO my_table(image_file) VALUES ('$file')";
  .
  // do your database insertion here as usual!
  .
}
// File was NOT uploaded successfully.
else {
  echo 'error : ' . $foo->error;
}
Reply

Your reply

Name *
Email 
Title *
Text *
CAPTCHA image
Enter the code displayed on the image:
Click on the image to generate another one if it is hard to read it. The case is important