We help IT Professionals succeed at work.

PHP/GDlib Image Upload Script

tamnic
tamnic asked
on
439 Views
Last Modified: 2008-02-01
Hi,

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,
Comment
Watch Question

Commented:
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

Commented:
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.
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION

Commented:
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

Commented:
Thanks landship your one of the Great Ones:)

I am running 5.

Thanks again,

Commented:
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.

Commented:
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

Commented:
Thanks again appreciate your time

Commented:
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 ***

<?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
                  ob_start();
                  imagejpeg($image_p);
                  $img_output = ob_get_contents();
                  ob_end_clean();

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

                  // Cleanup
                  unlink($file['photo']['tmp_name'][$i]);

            }  // 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:  admin@dhkold.com                */
      /* 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) {
                  $X=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;

                        imagesetpixel($res,$X,$Y,$COLOR[1]);
                        $X++;
                        $P += $BMP['bytes_per_pixel'];
                  }
                  $Y--;
                  $P+=$BMP['decal'];
            }

            //Fermeture du fichier (close the file)
            fclose($f1);

            return $res;
      }  // End function imagecreatefrombmp

}  // End class photoAlbum
?>

*** form.php ***

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

require_once('class_photoAlbum.php');
$album = new photoAlbum();
$db = new mysqli(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DATABASE);
      $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 ***

<?php
$db = new mysqli(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DATABASE);

    $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];
?>

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.