PHP/GDlib Image Upload Script

Posted on 2007-10-06
Last Modified: 2008-02-01

I am looking for a tutorial or a script that can do the below, I have found how-to's for each area I have described below but none show me how to place them together as a script. Any help would be appreciated.

Maybe someone has some script laying around which would meet the criteria I describe.

1.) I Will need the script in php; which will be using the GDlib.

2.) I need the script to Resize an Image and Create Thumbnails with Aspect Ratio.(will be stored in a BLOB)

3.) I need the script to convert gif,png,bmp into jpeg if needed, so when a user tries to upload an image this will convert automatically.

4.) Will need the code for uploading of 5 images(into mysql BLOB) at once to same id with different column name(image1,image2,etc...).

5.) Also, need code to show the BLOB images(individually) for each id.

Thanks for your time,
Question by:tamnic
    LVL 5

    Expert Comment

    I have a script that with a little modifying would do the trick.

    Is there a reason you want the image stored in a blob instead of uploaded to a folder and reference the url from the database?

    Author Comment

    Well Actually I have never used a BLOB before was just wanting try something different when storing images
    Thought this was an interesting way to learn more about mysql and its functionality.
    LVL 5

    Accepted Solution

    Fair enough, I've done both (though it was 3 years ago when I did the blob storage, I like uploading to a folder better). Giving you the complete code will take a couple days (since it's the weekend) following you're bullet points:
    1) I do have code laying around
    2) currently uploads to a folder, but I'll modify the code for you
    3) Currently only accepts .jpg, but I've wanted to allow uploading of other file types, so you're in luck that I need to update the code mentioned in step 1.
    4) Are the 5 images different images, and do you need thumbnails of each (10 total blobs consisting of 5 images and 5 thumbnails)
    5) Here you go:

    Add this img tag:
    <img src="show.php?position=<?= $BLOB_COLUMN; ?>id=<?= $ROW_ID; ?>">



    // getdata.php3 - by Florian Dittmer <>
    // Example php script to demonstrate the direct passing of binary data
    // to the user. More infos at
    // Syntax: getdata.php3?id=<id>

    $var_id = $HTTP_GET_VARS['id'];

    $var_position = $HTTP_GET_VARS['position'];



        $query = "select bin_data, filetype from images where id=$var_id AND position=$var_position";
        $result = @MYSQL_QUERY($query);

        $data = @MYSQL_RESULT($result,0,"bin_data");
        $type = @MYSQL_RESULT($result,0,"filetype");

        Header( "Content-type: $type");
        echo $data;
    LVL 5

    Expert Comment

    Wow, I wrote that show.php file a long time ago.

    What version of php are you running?

    My upload script uses mysqli so I'd need to make some changes if you are running <5.

    Author Comment

    Thanks landship your one of the Great Ones:)

    I am running 5.

    Thanks again,
    LVL 5

    Expert Comment

    You're welcome, you didn't have to award the points already, but give me a few days, and I'll have the full solution for you. Including updating the script for the show.php file.
    LVL 5

    Expert Comment

    I ran into a little problem since the gd library doesn't support .bmp images. I'm incorporating a function to make it work, but I won't have it done today. Just didn't want you to think I forgot.

    Author Comment

    Thanks again appreciate your time
    LVL 5

    Expert Comment

    Here you go, just change the mysql info, and ask me if you have any questions:

    *** sql for database table ***

    CREATE TABLE `imageblob` (
      `id` int(4) NOT NULL auto_increment,
      `name` varchar(30) NOT NULL default '',
      `image1` blob NOT NULL,
      `image2` blob NOT NULL,
      `image3` blob NOT NULL,
      `image4` blob NOT NULL,
      `image5` blob NOT NULL,
      PRIMARY KEY  (`id`)

    ***  class_photoAlbum.php ***

    // Set the constants
    define('MAX_WIDTH', '700');
    define('MAX_HEIGHT', '700');

    class photoAlbum {

          function photoAlbum() {

          }  // End function photAlbum (constructor)
          function addPhotos($db, $file, $post) {
                $build_query = '';
                for ($i = 0 ; $i < count($file['photo']['name']) ; $i++) {
                      if (!is_uploaded_file(@$file['photo']['tmp_name'][$i])) return 'The file was not uploaded properly.';

                      if (
                            (($file['photo']['type'][$i] == 'image/jpeg') && ($image = @imagecreatefromjpeg($file['photo']['tmp_name'][$i]))) ||
                            (($file['photo']['type'][$i] == 'image/gif') && ($image = @imagecreatefromgif($file['photo']['tmp_name'][$i]))) ||
                            (($file['photo']['type'][$i] == 'image/png') && ($image = @imagecreatefrompng($file['photo']['tmp_name'][$i]))) ||
                            (($file['photo']['type'][$i] == 'image/bmp') && ($image = @$this->imagecreatefrombmp($file['photo']['tmp_name'][$i])))
                            ) {} else { return 'This doesn&rsquo;t seem to be a valid image type: <strong>'.$file['photo']['type'][$i].'</strong>'; }

                      if (!(list($width_orig, $height_orig) = getimagesize($file['photo']['tmp_name'][$i]))) return 'Can\'t calculate image size, please try again.';

                      // Max image dimensions
                      $ratio_orig = $width_orig/$height_orig;
                      $width = MAX_WIDTH;
                      $height = MAX_HEIGHT;
                      if (($width_orig < $width) && ($height_orig < $height)) return 'The image is too small and will look distorted';
                      if ($width/$height > $ratio_orig) {
                            $width = round($height*$ratio_orig);
                      } else {
                            $height = round($width/$ratio_orig);

                      $tmpName = urlencode($file['photo']['name'][$i]);

                      // Resample and output
                      $image_p = imagecreatetruecolor($width, $height);
                      imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
                      // Catch image binary output
                      $img_output = ob_get_contents();

                      $build_query .= ", image".($i+1)."='".addslashes($img_output)."'";

                      // Cleanup

                }  // End for i count(photo)

                // Add the info to the database
                $query = "insert into imageblob set name='".$db->real_escape_string($post['name'])."'".$build_query;
                if ($result = $db->query($query)) {
                      return true;
                } else {
                      return $db->error;

          }  // End function addPhotos

          function imagecreatefrombmp($filename) {
          /* Fonction: ImageCreateFromBMP              */
          /* Author:   DHKold                          */
          /* Contact:                */
          /* Date:     The 15th of June 2005           */
          /* Version:  2.0B                            */

                //Ouverture du fichier en mode binaire (Open file in binary mode)
                if (! $f1 = fopen($filename,"rb")) return FALSE;

                //1 : Chargement des ent?tes FICHIER (load the file)
                $FILE = unpack("vfile_type/Vfile_size/Vreserved/Vbitmap_offset", fread($f1,14));
                if ($FILE['file_type'] != 19778) return FALSE;

                //2 : Chargement des ent?tes BMP (load the bitmap)
                $BMP = unpack('Vheader_size/Vwidth/Vheight/vplanes/vbits_per_pixel/Vcompression/Vsize_bitmap/Vhoriz_resolution/Vvert_resolution/Vcolors_used/Vcolors_important', fread($f1,40));

                $BMP['colors'] = pow(2,$BMP['bits_per_pixel']);
                if ($BMP['size_bitmap'] == 0) $BMP['size_bitmap'] = $FILE['file_size'] - $FILE['bitmap_offset'];
                $BMP['bytes_per_pixel'] = $BMP['bits_per_pixel']/8;
                $BMP['bytes_per_pixel2'] = ceil($BMP['bytes_per_pixel']);
                $BMP['decal'] = ($BMP['width']*$BMP['bytes_per_pixel']/4);
                $BMP['decal'] -= floor($BMP['width']*$BMP['bytes_per_pixel']/4);
                $BMP['decal'] = 4-(4*$BMP['decal']);
                if ($BMP['decal'] == 4) $BMP['decal'] = 0;

                //3 : Chargement des couleurs de la palette (load the color palette)
                $PALETTE = array();
                if ($BMP['colors'] < 16777216) {
                      $PALETTE = unpack('V'.$BMP['colors'], fread($f1,$BMP['colors']*4));

                //4 : Cr?ation de l'image (create the image)
                $IMG = fread($f1,$BMP['size_bitmap']);
                $VIDE = chr(0);

                $res = imagecreatetruecolor($BMP['width'],$BMP['height']);
                $P = 0;
                $Y = $BMP['height']-1;
                while ($Y >= 0) {
                      while ($X < $BMP['width']) {
                            if ($BMP['bits_per_pixel'] == 24) {
                                  $COLOR = unpack("V",substr($IMG,$P,3).$VIDE);
                            } elseif ($BMP['bits_per_pixel'] == 16) {
                                  $COLOR = unpack("n",substr($IMG,$P,2));
                                  $COLOR[1] = $PALETTE[$COLOR[1]+1];
                            } elseif ($BMP['bits_per_pixel'] == 8) {
                                  $COLOR = unpack("n",$VIDE.substr($IMG,$P,1));
                                  $COLOR[1] = $PALETTE[$COLOR[1]+1];
                            } elseif ($BMP['bits_per_pixel'] == 4) {
                                  $COLOR = unpack("n",$VIDE.substr($IMG,floor($P),1));
                                  if (($P*2)%2 == 0) $COLOR[1] = ($COLOR[1] >> 4); else $COLOR[1] = ($COLOR[1] & 0x0F);
                                  $COLOR[1] = $PALETTE[$COLOR[1]+1];
                            } elseif ($BMP['bits_per_pixel'] == 1) {
                                  $COLOR = unpack("n",$VIDE.substr($IMG,floor($P),1));
                                  if (($P*8)%8 == 0) $COLOR[1] =  $COLOR[1] >> 7;
                                  elseif (($P*8)%8 == 1) $COLOR[1] = ($COLOR[1] & 0x40)>>6;
                                  elseif (($P*8)%8 == 2) $COLOR[1] = ($COLOR[1] & 0x20)>>5;
                                  elseif (($P*8)%8 == 3) $COLOR[1] = ($COLOR[1] & 0x10)>>4;
                                  elseif (($P*8)%8 == 4) $COLOR[1] = ($COLOR[1] & 0x8)>>3;
                                  elseif (($P*8)%8 == 5) $COLOR[1] = ($COLOR[1] & 0x4)>>2;
                                  elseif (($P*8)%8 == 6) $COLOR[1] = ($COLOR[1] & 0x2)>>1;
                                  elseif (($P*8)%8 == 7) $COLOR[1] = ($COLOR[1] & 0x1);
                            $COLOR[1] = $PALETTE[$COLOR[1]+1];
                            } else return FALSE;

                            $P += $BMP['bytes_per_pixel'];

                //Fermeture du fichier (close the file)

                return $res;
          }  // End function imagecreatefrombmp

    }  // End class photoAlbum

    *** form.php ***

    if ($_SERVER['REQUEST_METHOD'] != 'POST') {
    <form action="form.php" enctype="multipart/form-data" method="post">
    for ($i = 0 ; $i < 5 ; $i++) {
          <p>Photo:<br /><input name="photo[]" type="file" /></p>
          <p>Name:<br /><input type="text" name="name" size="40" maxlength="80" /></p>
          <p><input type="submit" name="submit" value="Add Image!" /></p>
    } // End if form was not posted
    else {

    $album = new photoAlbum();
          $response = $album->addPhotos($db, $_FILES, $_POST);
          if ($response === true) {
                echo '<p>Images were uploaded</p>';
          } else {
                echo '<p>'.$response.'</p>';


    *** How to display the images ***

    <img src="show.php?image=image1&id=ROW_ID" />

    *** show.php ***


        $query = "select ".$db->real_escape_string($_GET['image'])." from imageblob where id='".$db->real_escape_string($_GET['id'])."'";
          $result = $db->query($query);
          $data = $result->fetch_assoc();

        Header("Content-type: image/jpeg");
        echo $data[$image];

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How your wiki can always stay up-to-date

    Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
    - Increase transparency
    - Onboard new hires faster
    - Access from mobile/offline

    As a database administrator, you may need to audit your table(s) to determine whether the data types are optimal for your real-world data needs.  This Article is intended to be a resource for such a task. Preface The other day, I was involved …
    Part of the Global Positioning System A geocode ( is the major subset of a GPS coordinate (, the other parts being the altitude and t…
    Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
    The viewer will learn how to count occurrences of each item in an array.

    760 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    12 Experts available now in Live!

    Get 1:1 Help Now