Miscellaneous
  Home arrow Miscellaneous arrow Page 2 - Thumbnails in PHP
Codewalker Forums 
  Tutorials  
Database Articles  
Miscellaneous  
Navigation Usability  
PEAR Articles  
Programming Basics  
Server Administration  
XML Tutorials  
  Reviews  
Database Book Reviews  
Linux Book Reviews  
Miscellaneous Reviews  
PHP Book Reviews  
PHP Software Reviews  
Server Admin Reviews  
SQL Tool Reviews  
  Code Gallery  
Content Management Code  
Contest Code  
Counters Code  
Database Code  
Date Time Code  
Discussion Board Code  
Email Code  
File Manipulation Code  
GUI Code  
Link Farm Code  
Miscellaneous Code  
Search Code  
Site Navigation Code  
User Management Code  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Download TestComplete 
Forums Sitemap 
Weekly Newsletter 
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
MISCELLANEOUS

Thumbnails in PHP
By: Codewalkers
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 9
    2003-04-30

    Table of Contents:
  • Thumbnails in PHP
  • Explanation
  • Conclusion

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Thumbnails in PHP - Explanation


    (Page 2 of 3 )

    We'll now proceed through the script and explain each block in excruciating detail. I hope you have caffeine ready, you may need it.

    <?php
    # Constants
    define(IMAGE_BASE'/var/www/html/mbailey/images');
    define(MAX_WIDTH150);
    define(MAX_HEIGHT150);
    ?>

    First we should define a few constants. IMAGE_BASE points to the directory from which images are to be served. Only images in or under this directory are available. MAX_WIDTH and MAX_HEIGHT specify the maximum size to which images will be shrunk. If an image is already smaller than these sizes, it is returned without modifications. Proportions are also retained so that if the width is reduced by a factor of 2, the height will be reduced by that same factor.

    <?php
    # Get image location
    $image_file str_replace('..'''$_SERVER['QUERY_STRING']);
    $image_path IMAGE_BASE "/$image_file";

    # Load image
    $img null;
    $ext strtolower(end(explode('.'$image_path)));
    if (
    $ext == 'jpg' || $ext == 'jpeg') {
        
    $img = @imagecreatefromjpeg($image_path);
    } else if (
    $ext == 'png') {
        
    $img = @imagecreatefrompng($image_path);
    # Only if your version of GD includes GIF support
    } else if ($ext == 'gif') {
        
    $img = @imagecreatefrompng($image_path);
    }
    ?>

    The image location is passed as the entire query string as explained above. To prevent people from accessing images outside of the specified path, the string replace function is used to remove any "..".

    The extension is checked to find out what type of image has been requested. GD has a number of different load functions. Each is of the form imageloadfrom[type](). I have included only the three most common image formats, though others can easily be added.

    If the extension is unrecognized or the specified file does not exist, $img is left empty. When this occurs, an error is generated (see below). The @ before the load functions suppresses errors so that the user won't be shown a page of garbage.

    NOTE: gif support isn't available in the newer versions of GD. If your version of GD does not support gif images, you should probably remove the lines for handling gif images.

    <?php
    # If an image was successfully loaded, test the image for size
    if ($img) {

        
    # Get image size and scale ratio
        
    $width imagesx($img);
        
    $height imagesy($img);
        
    $scale min(MAX_WIDTH/$widthMAX_HEIGHT/$height);
    ?>

    imagesx() and imagesy() return the width and height of the image respectively. The maximum size of the image is then divided by the actual size of the image. This results in a scaling ratio. This scaling ratio is multiplied by the actual image size in order to give the reduced size. This value is calculated for both the width and height seperately; though the smaller of the two is used. By using the same value for both width and height, we preserve the correct proportions.

    <?php
        
    # If the image is larger than the max shrink it
        
    if ($scale &lt1) {
            
    $new_width floor($scale*$width);
            
    $new_height floor($scale*$height);

            
    # Create a new temporary image
            
    $tmp_img imagecreatetruecolor($new_width$new_height);

            
    # Copy and resize old image into new image
            
    imagecopyresized($tmp_img$img0000,
                             
    $new_width$new_height$width$height);
            
    imagedestroy($img);
            
    $img $tmp_img;
        }
    }
    ?>

    If the scale ratio is greater than or equal to 1 the image does not need to be modified in any way. Otherwise, the image must be reduced in size by that value. The new image size is generated by multiplying the scale by the current size.

    Using these new dimensions a buffer image is created using imagecreatetruecolor(). If you are using a GD library prior to 2.0, you will need to change this function to imagecreate(). The true color version of this function was added in 2.0 to preserve color integrity when parts of an image are copied, which we are about to do. The older function will still work fine for many images, but high color photos and the like may not maintain the correct colors using the older function.

    The original image is then resized into the buffer image. Since we will now be using this new image, we are able to free the original image with imagedestroy(). The buffer image is then renamed to $img.

    <?php
    # Create error image if necessary
    if (!$img) {
        
    $img imagecreate(MAX_WIDTHMAX_HEIGHT);
        
    imagecolorallocate($img,0,0,0);
        
    $c imagecolorallocate($img,70,70,70);
        
    imageline($img,0,0,MAX_WIDTH,MAX_HEIGHT,$c2);
        
    imageline($img,MAX_WIDTH,0,0,MAX_HEIGHT,$c2);
    }
    ?>

    As was explained earlier, if the image's extension was unrecognizable, or the file did not exist all together, $img was left empty. If this is the case, we need to generate a place holder image to notify the user that the image they requested was unavailable. We do this by drawing a black box with a gray X through the middle. You may want to make this more explicit, by adding text or even redirecting the browser to a premade image.

    <?php
    # Display the image
    header("Content-type: image/jpeg");
    imagejpeg($img);
    ?>

    The image is finally displayed to the user in jpeg format.

    More Miscellaneous Articles
    More By Codewalkers


       · Hey there!http://bravura.bueza.com/gallery.phpI have a problem with image...
       · Hi, to get rid of any distortion, I just renamed imagecopyresized, to...
       · This is a great tutorial. Thank you. But I'm having issues to display the image,...
       · Hello,thanks for your tutorial.I just wanted to mention that you must quote...
       · Does it support client side caching of the re-sized images, so that a user...
       · When I basically cut and paste the tutorial, i'm getting the following...
       · I have the same problem... Any help would be much appreciated!
       · < is the culprit. I only post this so late for anybody coming across this great...
       · when I ran the code with all the changes, I got a black 150 X 150 box instead of a...
       · hei,,i can not get any pictures...
       · If you are having problems (like black box) make sure the directory is like you...
     

    MISCELLANEOUS ARTICLES

    - Using PHP to Stream MP3 Files and Prevent Il...
    - 10 Must Have Firefox Improvements
    - All About OpenOffice 3.0
    - Shell Script Writing
    - Loops in the UNIX Shell
    - The Test in the UNIX Shell
    - Data Streams and the UNIX Shell
    - Control Mechanisms of the UNIX Shell
    - Variables Within the UNIX Shell
    - The Shell and UNIX
    - In Detail: UNIX File Systems
    - Rights Management in UNIX
    - UNIX File Systems
    - The Terminal in UNIX
    - Operating Systems and UNIX





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 5 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek