NYCPHP Meetup

NYPHP.org

[nycphp-talk] Resample Image on the Fly

Dan Cech dcech at phpwerx.net
Mon Jan 29 10:21:26 EST 2007


Randal Rust wrote:
> On 1/29/07, Dan Cech <dcech at phpwerx.net> wrote:
> 
>> I'm not entirely sure what you're asking...can you give us a general
>> idea of what you're trying to achieve?
> 
> Sure. Take a look here:
> 
> http://r2test3.com/project_detail.php?rec=3
> 
> What I have done is used getimagesize(0 to get the original width and
> height of the image. Then I modify those values proportionally with a
> script I wrote and do this:
> 
> <img src="'.$url.'" width="'.$newW.'" height="'.$newH.'" />
> 
> The issue is that the images don't look as clear as I'd like them to
> after resizing. I think they just need to be resampled.

Randal,

You can easily use GD to resample images on the fly, but it will be slow
and take a heavy toll on the webserver if you're getting any kind of
traffic.

The trick is to write a php script which accepts an image name as a
parameter, loads the image into GD and outputs the resampled version
directly to the browser.

The more efficient way to do this is to cache the generated image on
disk, and only regenerate it when the source image changes (I do this by
comparing the last modified timestamps of the source image and the
resampled version in the cache).

Here is a function to get you started, which takes an image file,
resamples it to the specified height and width, and then either writes
it to the named file or outputs it to the browser.

Dan

function _resize_image_gd2($imgfile,$w = NULL,$h = NULL,$format =
'png',$destfile = NULL)
{
  $size = getimagesize($imgfile);
  $s_w = $size[0];
  $s_h = $size[1];

  switch ($size[2]) {
    case 1: // GIF
      $src = imagecreatefromgif($imgfile);
      break;
    case 2: // JPEG
      check_jpeg($imgfile);
      $src = imagecreatefromjpeg($imgfile);
      break;
    case 3: // PNG
      $src = imagecreatefrompng($imgfile);
      break;
    default:
      $src = imagecreatefromstring(file_get_contents($imgfile));
  }

  if (!is_resource($src)) {
    return false;
  }

  $dest = imagecreatetruecolor($w,$h);
  if (!is_resource($dest)) {
    return false;
  }

  imageantialias($dest,TRUE);

  imagecopyresampled($dest,$src,0,0,0,0,$w,$h,$s_w,$s_h);

  if (isset($destfile)) {
    switch (strtolower($format)) {
      case 'jpg':
      case 'jpeg':
        imagejpeg($dest,$destfile);
        break;
      case 'png':
        imagepng($dest,$destfile);
        break;
      default:
        return false;
    }
  } else {
    switch (strtolower($format)) {
      case 'jpg':
      case 'jpeg':
        imagejpeg($dest);
        break;
      case 'png':
        imagepng($dest);
        break;
      default:
        return false;
    }
  }

  return true;
}



More information about the talk mailing list