PHP image resize

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
edzin
Forum Newbie
Posts: 3
Joined: Fri Jan 30, 2009 10:35 am

PHP image resize

Post by edzin »

I am trying to create an upload form where I can upload an image and it make 4 copies of the file, resizes it and puts it into 4 different folders. I found some php that works, but the image quality of the resized images is terrible. Can you make any suggestions on how to resize the images without loosing quality? Below is the php and a before and after of the image for you to look at. I am a total noob at php so any help you can offer would be much appreciated. Thanks!

http://www.michaeldfoley.com/postlet/images/18.jpg
http://www.michaeldfoley.com/postlet/images/high/18.jpg

Code: Select all

<?php
$idir = "images/";   // Path To Images Directory
$hdir = "images/high/";   // Path To Thumbnails Directory
$hheight = "800";   // Maximum Height For Thumbnail Images
$mdir = "images/medium/";   // Path To Thumbnails Directory
$mheight = "600";   // Maximum Height For Thumbnail Images
$ldir = "images/low/";   // Path To Thumbnails Directory
$lheight = "450";   // Maximum Height For Thumbnail Images
$tdir = "images/tiny/";   // Path To Thumbnails Directory
$theight = "300";   // Maximum Height For Thumbnail Images
 
if (!isset($_GET['subpage'])) {   // Image Upload Form Below   ?>
  <form method="post" action="upload-size.php?subpage=upload" enctype="multipart/form-data">
   File:<br />
  <input type="file" name="imagefile" class="form">
  <br /><br />
  <input name="submit" type="submit" value="Submit" class="form">  <input type="reset" value="Clear" class="form">
  </form>
<? } else  if (isset($_GET['subpage']) && $_GET['subpage'] == 'upload') {   // Uploading/Resizing Script
  $url = $_FILES['imagefile']['name'];   // Set $url To Equal The Filename For Later Use
  if ($_FILES['imagefile']['type'] == "image/jpg" || $_FILES['imagefile']['type'] == "image/jpeg" || $_FILES['imagefile']['type'] == "image/pjpeg") {
    $file_ext = strrchr($_FILES['imagefile']['name'], '.');   // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php
    $copy = copy($_FILES['imagefile']['tmp_name'], "$idir" . $_FILES['imagefile']['name']);   // Move Image From Temporary Location To Permanent Location
    if ($copy) {   // If The Script Was Able To Copy The Image To It's Permanent Location
      print 'Image uploaded successfully.<br /><br />';   // Was Able To Successfully Upload Image
      
      $shimg = imagecreatefromjpeg("$idir" . $url);   // Make A New Temporary Image To Create The Thumbanil From
      $hcurrwidth = imagesx($shimg);   // Current Image Width
      $hcurrheight = imagesy($shimg);   // Current Image Height
      
         $hzoom = $hheight / $hcurrheight;   // Length Ratio For Width
         $hnewheight = $hheight;   // Height Is Equal To Max Height
         $hnewwidth = $hcurrwidth * $hzoom;   // Creates The New Width
      
      $dhimg = imagecreate($hnewwidth, $hnewheight);   // Make New Image For Thumbnail
      imagetruecolortopalette($shimg, false, 255);   // Create New Color Pallete
      $hpalsize = ImageColorsTotal($shimg);
      for ($i = 0; $i < $hpalsize; $i++) {   // Counting Colors In The Image
       $hcolors = ImageColorsForIndex($shimg, $i);   // Number Of Colors Used
       ImageColorAllocate($dhimg, $hcolors['red'], $hcolors['green'], $hcolors['blue']);   // Tell The Server What Colors This Image Will Use
      }
      imagecopyresized($dhimg, $shimg, 0, 0, 0, 0, $hnewwidth, $hnewheight, $hcurrwidth, $hcurrheight);   // Copy Resized Image To The New Image (So We Can Save It)
      imagejpeg($dhimg, "$hdir" . $url);   // Saving The Image
      imagedestroy($shimg);   // Destroying The Temporary Image
      imagedestroy($dhimg);   // Destroying The Other Temporary Image
      print 'High image created successfully.<br />';   // Resize successful
        
      $smimg = imagecreatefromjpeg("$idir" . $url);   // Make A New Temporary Image To Create The Thumbanil From
      $mcurrwidth = imagesx($smimg);   // Current Image Width
      $mcurrheight = imagesy($smimg);   // Current Image Height
      
         $mzoom = $mheight / $mcurrheight;   // Length Ratio For Width
         $mnewheight = $mheight;   // Height Is Equal To Max Height
         $mnewwidth = $mcurrwidth * $mzoom;   // Creates The New Width
      
      $dmimg = imagecreate($mnewwidth, $mnewheight);   // Make New Image For Thumbnail
      imagetruecolortopalette($smimg, false, 255);   // Create New Color Pallete
      $mpalsize = ImageColorsTotal($smimg);
      for ($i = 0; $i < $mpalsize; $i++) {   // Counting Colors In The Image
       $mcolors = ImageColorsForIndex($smimg, $i);   // Number Of Colors Used
       ImageColorAllocate($dmimg, $mcolors['red'], $mcolors['green'], $mcolors['blue']);   // Tell The Server What Colors This Image Will Use
      }
      imagecopyresized($dmimg, $smimg, 0, 0, 0, 0, $mnewwidth, $mnewheight, $mcurrwidth, $mcurrheight);   // Copy Resized Image To The New Image (So We Can Save It)
      imagejpeg($dmimg, "$mdir" . $url);   // Saving The Image
      imagedestroy($smimg);   // Destroying The Temporary Image
      imagedestroy($dmimg);   // Destroying The Other Temporary Image
      print 'Medium image created successfully.<br />';   // Resize successful
      
      $slimg = imagecreatefromjpeg("$idir" . $url);   // Make A New Temporary Image To Create The Thumbanil From
      $lcurrwidth = imagesx($slimg);   // Current Image Width
      $lcurrheight = imagesy($slimg);   // Current Image Height
      
         $lzoom = $lheight / $lcurrheight;   // Length Ratio For Width
         $lnewheight = $lheight;   // Height Is Equal To Max Height
         $lnewwidth = $lcurrwidth * $lzoom;   // Creates The New Width
      
      $dlimg = imagecreate($lnewwidth, $lnewheight);   // Make New Image For Thumbnail
      imagetruecolortopalette($slimg, false, 255);   // Create New Color Pallete
      $lpalsize = ImageColorsTotal($slimg);
      for ($i = 0; $i < $lpalsize; $i++) {   // Counting Colors In The Image
       $lcolors = ImageColorsForIndex($slimg, $i);   // Number Of Colors Used
       ImageColorAllocate($dlimg, $lcolors['red'], $lcolors['green'], $lcolors['blue']);   // Tell The Server What Colors This Image Will Use
      }
      imagecopyresized($dlimg, $slimg, 0, 0, 0, 0, $lnewwidth, $lnewheight, $lcurrwidth, $lcurrheight);   // Copy Resized Image To The New Image (So We Can Save It)
      imagejpeg($dlimg, "$ldir" . $url);   // Saving The Image
      imagedestroy($slimg);   // Destroying The Temporary Image
      imagedestroy($dlimg);   // Destroying The Other Temporary Image
      print 'Low image created successfully.<br />';   // Resize successful
      
      $simg = imagecreatefromjpeg("$idir" . $url);   // Make A New Temporary Image To Create The Thumbanil From
      $currwidth = imagesx($simg);   // Current Image Width
      $currheight = imagesy($simg);   // Current Image Height
      
         $zoom = $theight / $currheight;   // Length Ratio For Width
         $newheight = $theight;   // Height Is Equal To Max Height
         $newwidth = $currwidth * $zoom;   // Creates The New Width
      
      $dimg = imagecreate($newwidth, $newheight);   // Make New Image For Thumbnail
      imagetruecolortopalette($simg, false, 255);   // Create New Color Pallete
      $palsize = ImageColorsTotal($simg);
      for ($i = 0; $i < $palsize; $i++) {   // Counting Colors In The Image
       $colors = ImageColorsForIndex($simg, $i);   // Number Of Colors Used
       ImageColorAllocate($dimg, $colors['red'], $colors['green'], $colors['blue']);   // Tell The Server What Colors This Image Will Use
      }
      imagecopyresized($dimg, $simg, 0, 0, 0, 0, $newwidth, $newheight, $currwidth, $currheight);   // Copy Resized Image To The New Image (So We Can Save It)
      imagejpeg($dimg, "$tdir" . $url);   // Saving The Image
      imagedestroy($simg);   // Destroying The Temporary Image
      imagedestroy($dimg);   // Destroying The Other Temporary Image
      print 'Tiny image created successfully.<br />';   // Resize successful
      
    } else {
      print '<font color="#FF0000">ERROR: Unable to upload image.</font>';   // Error Message If Upload Failed
    }
  } else {
    print '<font color="#FF0000">ERROR: Wrong filetype (has to be a .jpg or .jpeg. Yours is ';   // Error Message If Filetype Is Wrong
    print $file_ext;   // Show The Invalid File's Extention
    print '.</font>';
  }
} ?>
User avatar
infolock
DevNet Resident
Posts: 1708
Joined: Wed Sep 25, 2002 7:47 pm

Re: PHP image resize

Post by infolock »

here is a class i have written for doing exactly that...
of course... it requires the GD library to be installed (which I assume you have installed...)

Code: Select all

 
<?php
/**
 * @author Jonathon Hibbard
 * Generates a JPG, PNG, or GIF thumbnail on the fly.
 * 
 * @requires PHP 5.x or above..
 */
class imagethumbnail {
 
  public $x, $y, $filename, $image, $thumbnail;
  public $errors = array();
 
  function __construct($filename, $new_filename, $ext, $x, $y) {
    if(!is_file($filename)) {
      $this->errors[] = "INVALID FILENAME:: $filename";
      return false;
    }
 
    $this->x = $x;
    $this->y = $y;
 
    $this->filename = $filename;
    $this->open();
 
    switch($ext) {
      case 'gif':
        $this->imagegif($new_filename);
      break;
      case 'jpg':
        $this->imagejpeg($new_filename);
      break;
      case 'png':
        $this->imagepng($new_filename);
      break;
    }
  }
 
 
  /**
   * Opens the file on the fileserver we are wanting to generate a thumbnail for.
   *
   * @param string,path  $filename  //The actual location and filename of the image.
   */
  public function open() {
    $imageinfo = array();
    $imageinfo = getimagesize($this->filename, $imageinfo);
 
    $this->old_x = $imageinfo[0];
    $this->old_y = $imageinfo[1];
 
    switch(intval($imageinfo[2])) {
      case 1: $this->image = imagecreatefromgif($this->filename);  break;
      case 2: $this->image = imagecreatefromjpeg($this->filename); break;
      case 3: $this->image = imagecreatefrompng($this->filename);  break;
    }
  }
 
  /**
   * Sets the width of the image.
   *
   * @param  width    $x
   * @return $this->x //Returns the verified width.
   */
  public function setX($x) {
    $this->x = $x;
  }
 
  /**
   * Sets the height of the image.
   *
   * @param  height    $y
   * @return $this->y //Returns the verified beight.
   */
  public function setY($y = "") {
    $this->y = $y;
  }
 
  /**
   * Generates a GIF image with the name of $filename on the fileserver from the thumbnail that is residing in the output buffer.
   *
   * @param  string $filename  //The filename we are wanitng to give the image.
   */
  public function imagegif($filename = "") {
    if(!isset($this->thumbnail)) {
      $this->generate();
    }
 
    imagetruecolortopalette($this->thumbnail, 0, 255);
 
    if(empty($filename)) {
      imagegif($this->thumbnail);
    } else {
      imagegif($this->thumbnail, $filename);
    }
  }
 
  /**
   * Generates a JPG image with the name of $filename on the fileserver from the thumbnail that is residing in the output buffer.
   *
   * @param  string $filename  //The filename we are wanitng to give the image.
   */
  public function imagejpeg($filename = "", $quality = 80) {
    if(!isset($this->thumbnail)) {
      $this->generate();
    }
 
    imagejpeg($this->thumbnail, $filename, $quality);
  }
 
  /**
   * Generates a PNG image with the name of $filename on the fileserver from the thumbnail that is residing in the output buffer.
   *
   * @param  string $filename  //The filename we are wanitng to give the image.
   */
  public function imagepng($filename = "", $quality = 80) {
    if(!isset($this->thumbnail)) {
      $this->generate();
    }
    if(empty($filename)) {
      imagepng($this->thumbnail);
    } else {
      imagepng($this->thumbnail, $filename, $quality);
    }
  }
 
  /**
   * Generates the thumbnail and stores it in the output buffer temporarily.
   */
  private function generate() {
    if($this->x > 0 && $this->y > 0) {
      $new_x = $this->x;
      $new_y = $this->y;
    } elseif(intval($this->x) > 0) {
      $new_x = $this->x;
      $new_y = ($this->x / $this->old_x) * $this->old_y;
    } else {
      $new_x = ($this->y / $this->old_y) * $this->old_x;
      $new_y = $this->y;
    }
 
    $this->thumbnail = imagecreatetruecolor($new_x, $new_y);
    $white = imagecolorallocate($this->thumbnail, 255, 255, 255);
 
    imagefill($this->thumbnail,0,0,$white);
    imagecopyresampled($this->thumbnail, $this->image, 0, 0, 0, 0, $new_x, $new_y, $this->old_x, $this->old_y);
  }
}
?>
 
Usage would be something like this:

Code: Select all

 
<?php
  ##################  THUMBNAIL GENERATION  #################
  include_once('thumbnail.php');
  $x = 180;
  $y = 150;
 
  $original_filename = "/var/www/mytest.gif";
  $filename_for_thumbnail = "/var/www/mytest_tn.gif";
  $ext = "gif";
  $tn = new imagethumbnail($original_filename, $filename_for_thumbnail, $file_type, $x, $y);
 
  $original_filename = "/var/www/mytest2.gif";
  $filename_for_thumbnail = "/var/www/mytest2_tn.gif";
  $ext = "gif";
  $tn = new imagethumbnail($original_filename, $filename_for_thumbnail, $file_type, $x, $y);
 
  $original_filename = "/var/www/mytest3.gif";
  $filename_for_thumbnail = "/var/www/mytest3_tn.gif";
  $ext = "gif";
  $tn = new imagethumbnail($original_filename, $filename_for_thumbnail, $file_type, $x, $y);
?>
 
Hope this helps..
Post Reply