PHP/GDlib Image Upload Script

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,
tamnicAsked:
Who is Participating?
 
landshipCommented:
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; ?>">


show.php:

<?php

// getdata.php3 - by Florian Dittmer <dittmer@gmx.net>
// Example php script to demonstrate the direct passing of binary data
// to the user. More infos at http://www.phpbuilder.com
// Syntax: getdata.php3?id=<id>

$var_id = $HTTP_GET_VARS['id'];

$var_position = $HTTP_GET_VARS['position'];

    @MYSQL_CONNECT("localhost","USERNAME","PASSWORD");

    @mysql_select_db("DATABASE_NAME");

    $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;
?>
0
 
landshipCommented:
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?
0
 
tamnicAuthor 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.
0
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
landshipCommented:
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.
0
 
tamnicAuthor Commented:
Thanks landship your one of the Great Ones:)

I am running 5.

Thanks again,
0
 
landshipCommented:
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.
0
 
landshipCommented:
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.
0
 
tamnicAuthor Commented:
Thanks again appreciate your time
0
 
landshipCommented:
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];
?>
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.