| Subcribe via RSS

Image Thumbnail Creator

October 17th, 2007 Posted in PHP

Like many other people, I found Mike Lopez's image thumbnail script quite useful. He has taken the time to go through the brain-crunching algorithm to create image proportional image thumbnails when given a max height/width. Although this script is very handy, it was lacking in a few areas, such as transparent PNG and GIF support, as well as the un-needed resize if the image was smaller than the requested dimensions. I hope I have "helped" in this situation by modifying the script so that it handles such requests. Credit for the transparency support goes to Martin Schmidt (icheee).

One modification I made that is important to note is that the image is now fed through with the SRC variable, rather than the IMG variable. Thanks Mike for this script and I hope my updates really help.

PHP:
  1. <?php
  2. /*
  3. JPEG / GIF / PNG Resizer / Image Viewer
  4. Parameters (passed via URL):
  5. src = path / url of jpeg or png image file
  6. percent = if this is defined, image is resized by it's
  7.           value in percent (i.e. 50 to divide by 50 percent)
  8. w = image width
  9. h = image height
  10. thumb: set = displays thumbnail.
  11.         not set = displays original image.
  12. force: by default this script will constrain the image proportions. If you wish to
  13.         force with width/height settings, set &force in the URL
  14.         width and height and thumb MUST be set.
  15. Requires the PHP GD Extension
  16. Originally By: Michael John G. Lopez - www.sydel.net
  17. Modified By: Brian DiChiara - www.briandichiara.com
  18. Modifications:
  19. Supports Transparent PNG and GIF
  20. Does not resize images smaller than specified w/h
  21. Supports Remote files (http://www.notyoursite.com/image.jpg)
  22. Usage Example:
  23. <img src="image.php?src=myimage.jpg&thumb&w=200&h=200" border="0" alt="my image" />
  24. */
  25.  
  26. function getExtension($f){
  27.     $pos = strrpos($f, '.');
  28.     if(!$pos) {
  29.         return '';
  30.     }
  31.     $str = substr($f, $pos + 1, strlen($f));
  32.     return strtolower($str);
  33. }
  34.  
  35. $img = $_GET['src'];
  36. $ext = strtolower(getExtension($_GET['src']));
  37. $percent = (isset($_GET['percent']) && !empty($_GET['percent'])) ? $_GET['percent'] : false;
  38. //$constrain = (isset($_GET['constrain'])) ? ($_GET['constrain'] == 0 || $_GET['constrain'] == "false" || $_GET['constrain'] == "0") ? false : true : true;
  39. $force = (isset($_GET['force']) && isset($_GET['w']) && isset($_GET['h']) && !empty($_GET['w']) && !empty($_GET['h'])) ? true : false;
  40.  
  41. $remote = @file ($img);
  42. if($remote){
  43.     $fp = @fopen ($img, 'rb');
  44.     $data = '';
  45.     while (!feof ($fp)){
  46.         $data .= fgets($fp, 4096);
  47.     }
  48.     $src = @imagecreatefromstring($data);
  49.     $sw = @imagesx($src);
  50.     $sh = @imagesy($src);
  51. } else {
  52.     $dims = @getimagesize($img); // get width/height of original image
  53.    
  54.     $sw = $dims[0]; //returns width
  55.     $sh = $dims[1]; //returns height
  56. }
  57.  
  58. $w = (isset($_GET['w']) && !empty($_GET['w'])) ? $_GET['w'] : 0; //desired maximum width
  59. $h = (isset($_GET['h']) && !empty($_GET['h'])) ? $_GET['h'] : 0; //desired maximum height
  60.  
  61. $resize = false; //assume no resize is needed
  62.  
  63. if ($percent> 0) {
  64.     // calculate resized height and width if percent is defined
  65.     $percent = $percent * 0.01;
  66.     $w = $sw * $percent;
  67.     $h = $sh * $percent;
  68. } else {
  69.     $resize = (($sh> $h && isset($h) && $h != 0) || ($sw> $w && isset($w) && $w != 0)) ? true : $resize;
  70.     $resize = ($force) ? true : $resize;
  71.     if(($resize && isset($_GET['thumb']))){
  72.         if (isset ($w) && (!isset ($h) || $h == 0)) {
  73.             // autocompute height if only width is set
  74.             $h = (100 / ($sw / $w)) * .01;
  75.             $h = @round ($sh * $h);
  76.         } elseif (isset ($h) && (!isset ($w) || $w == 0)) {
  77.             // autocompute width if only height is set
  78.             $w = (100 / ($sh / $h)) * .01;
  79.             $w = @round ($sw * $w);
  80.         } elseif (isset ($h) && isset ($w) && !$force) {
  81.             // get the smaller resulting image dimension if both height
  82.             // and width are set and $constrain is also set
  83.             $hx = (100 / ($sw / $w)) * .01;
  84.             $hx = @round ($sh * $hx);
  85.    
  86.             $wx = (100 / ($sh / $h)) * .01;
  87.             $wx = @round ($sw * $wx);
  88.    
  89.             if ($hx <$h) {
  90.                 $h = (100 / ($sw / $w)) * .01;
  91.                 $h = @round ($sh * $h);
  92.             } else {
  93.                 $w = (100 / ($sh / $h)) * .01;
  94.                 $w = @round ($sw * $w);
  95.             }
  96.         }
  97.     } else {
  98.         $w = $sw;
  99.         $h = $sh;
  100.     }
  101. }
  102.  
  103. switch ($ext){
  104.     case "jpg"  : $type = "jpeg";    break;
  105.     case "bmp"  : $type = "x-ms-bmp"break;
  106.     case "png"  : $type = "x-png"; break;
  107.     case "tif"  : $type = "x-tiff";    break;
  108.     case "ico"  : $type = "x-icon";    break;
  109.     default  :    $type = $ext;      break;
  110. }
  111.  
  112.  
  113. if((!$resize || !isset($_GET['thumb'])) && !remote){
  114.     //display contents
  115.     header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
  116.     header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  117.     header("Cache-Control: no-store, no-cache, must-revalidate");
  118.     header("Cache-Control: post-check=0, pre-check=0", false);
  119.     header("Pragma: no-cache");
  120.     header('Content-Length: '.filesize($img));
  121.     header('Content-type: image/' . $type);
  122.     readfile($img);
  123. } else {
  124.     $im = ($remote) ? $src : false;
  125.     switch ($ext){
  126.         case "jpg"  :
  127.         case "jpeg" :    $im = @imagecreatefromjpeg($img);   break;
  128.         case "wbmp" :    $im = @imagecreatefromwbmp($img);   break;
  129.         case "png"  : $im = @imagecreatefrompng($img); break;
  130.         case "gif"  : $im = @imagecreatefromgif($img); break;
  131.         default  :    $im = false; break;
  132.     }
  133.    
  134.     header('Content-type: image/' . $type);
  135.    
  136.     if (!$im) {
  137.         // just return the contents of the actual image.
  138.         readfile ($img);
  139.     } else {
  140.         // Create the resized image destination
  141.         $thumb = @imagecreatetruecolor ($w, $h);
  142.        
  143.         //preserve alpha opacity - thanks to Martin Schmidt
  144.         $colorcount = @imagecolorstotal($im);
  145.         @imagetruecolortopalette($thumb,true,$colorcount);
  146.         @imagepalettecopy($thumb,$im);
  147.         $transparentcolor = @imagecolortransparent($im);
  148.         @imagefill($thumb,0,0,$transparentcolor);
  149.         @imagecolortransparent($thumb,$transparentcolor);
  150.        
  151.         // Copy from image source, resize it, and paste to image destination
  152.         @imagecopyresampled ($thumb, $im, 0, 0, 0, 0, $w, $h, $sw, $sh);
  153.        
  154.         // Output resized image
  155.         switch ($ext){
  156.             case "wbmp" :    @imagewbmp ($thumb);    break;
  157.             case "png"  : @imagepng ($thumb);    break;
  158.             case "gif"  : @imagegif ($thumb);    break;
  159.             default  :    @imagejpeg ($thumb);    break;
  160.         }
  161.        
  162.         imagedestroy($thumb);
  163.         imagedestroy($im);
  164.     }
  165. }
  166. ?>

Last Update: 2008-01-10 23:12 CST
* fixed resize issue where only 1 dimension was provided.

11 Responses to “Image Thumbnail Creator”

  1. Al Says:

    You need to change the filename to download from image.php to another extension like image.phps in order for people to download…

    I can’t copy and paste the actual text above because the text because all crumpled up.


  2. briandichiara Says:

    I changed the code highlighter plugin to something a little better. You should be able to copy it now.


  3. Al Says:

    I have made sure already that the image does exist. In my case, the image is on my server, but it will not always be this case. I’d like this to work with all images on any server.

    Thanks.


  4. briandichiara Says:

    The script has been updated to support remote images. Should work the exact same, just use a remote file URL rather than a relative URL in the SRC variable. Let me know if you have any questions.


  5. cici Says:

    Hi,

    great script, thanks for this!!!

    need a feature, crop image

    Thanks!


  6. Framboos Says:

    Great script! Especially the feature to resize remote images.
    Haven’t seen that in the other scripts I’ve looked at (http://www.darrenhoyt.com/2008/04/02/timthumb-php-script-released/, http://shiftingpixel.com/2008/03/03/smart-image-resizer/).

    But those scripts do have file caching, is there anyone who knows how to add that to this script? I’ve tried combining some parts but not succesfully yet, so far…


  7. MuddyFrog » Blog Archive » Image Resizer Says:


  8. Joe Says:

    Thank you, thank you, thank you for modifying this script. It works perfectly.


  9. bjarne Says:

    Looks very nice Brian!

    Have not tested it yet, but looks very nice. Just one question: What about at cache for the tumbnails? Is it just to change sometning in the code, make a folder (777) and it would work?

    Why cache you said? Slow remote server…

    Thanks:)


  10. Alexander Says:

    Dear Brian, just a question since you are (and I am not, not yet) a CodeIgnitor user. I noticed that there is also an image maniputalor class in CI. Can that not do what your script above does?

    Btw, nice that you also discovered PHPDesigner :)


  11. briandichiara Says:

    Yes, Alexander. This post was written LONG before I discovered CI. CI rocks, although I actually haven’t messed with CI’s Image Manipulation Library very much. (not at all actually) You should give it a try!


Leave a Reply

Preview: