Resize Image to Different Aspect Ratio On-The-Fly

Jan 2, 2009 | Tags: PHP, Image | del.icio.us del.icio.us | digg Digg

Use this script to resize your image to different aspect ratio on the fly. For instance, when you have a 1024x800 wallpaper and you want to create a 120x120 thumbnail of it. This is done by cropping the source image to match the thumbnail's aspect ratio first, then resizing the cropped image to the thumbnail size.

Listing 1: image.php

  1. <?php
  2. /**
  3.  * Resize Image with Different Aspect Ratio
  4.  *
  5.  * Author:  Nash
  6.  * License: GPL
  7.  * Website: http://nashruddin.com
  8.  */
  9.  
  10. header("Content-type: image/jpeg");
  11.  
  12. /* get parameters */
  13. $f = $_GET['f'];
  14. $w = $_GET['w'];
  15. $h = $_GET['h'];
  16.  
  17. /* expand the thumbnail's aspect ratio
  18.    to fit the width/height of the image */
  19. $in = @getimagesize($f);
  20. $sw = $in[0] / $w;
  21. $sh = $in[1] / $h;
  22. $s  = $sw < $sh ? $sw : $sh;
  23.  
  24. /* crop the center of the image */
  25. $x0 = floor( ( $in[0] - ( $w * $s ) ) * 0.5 );
  26. $y0 = floor( ( $in[1] - ( $h * $s ) ) * 0.5 );
  27.  
  28. /* support JPG, PNG and GIF */
  29. $im = @imagecreatefromjpeg($f) or
  30. $im = @imagecreatefrompng($f) or
  31. $im = @imagecreatefromgif($f) or
  32. $im = false;
  33.  
  34. if (!$im) {
  35.     /* something went wrong, output the image */
  36.     readfile($f);
  37. } else {
  38.     /* create thumbnail */
  39.     $thumb = @imagecreatetruecolor($w, $h);
  40.     @imagecopyresampled($thumb, $im, 0, 0, $x0, $y0, $w, $h, ($w * $s), ($h * $s));
  41.     @imagejpeg($thumb);
  42. }

All you have to do is save the listing above to image.php, and use it like this:

<img src="image.php?w=120&h=120&f=wallpaper.jpg" border="0" />

Related Articles

2 Comments

Salman on Mar 2, 2009:

The following example does the same with uploaded images:

http://911-need-code-help.blogspot.com/2008/10/resize-images-using-phpgd-library.html

The entire image is resized to "best fit" in the specified thumbnail width and height.

Richard Allen on Mar 18, 2009:

Thanks for this script its very easy implement and works very well.

Exactly what I needed, keep up the good work.

Leave a comment

Name (required)
Email (will not be published) (required)
Website

Characters left = 1000