Re: function to resize images

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Bosky, Dave wrote:
> Does anyone have a nice function that will resize an uploaded image to
> specific width/height dimensions?

Not a function, per se, but I use this script:

<?php
  $path = $_SERVER['PATH_INFO'];
  ereg(".*/target/([0-9]*).*", $path, $target);
  $target = isset($target[1]) && $target[1] ? $target[1] : 50;
  $path = ereg_replace("/target/[0-9]*", "", $path);

  list($junk1, $junk2, $type) = @getimagesize($path);
  $type = isset($type) && $type ? $type : IMAGETYPE_JPEG;
  switch ($type){
    case IMAGETYPE_JPEG: $fullsize = imagecreatefromjpeg($path); break;
    case IMAGETYPE_GIF: $fullsize = imagecreatefromgif($path); break;
    case IMAGETYPE_PNG: $fullsize = imagecreatefrompng($path); break;
  }
  $width = imagesx($fullsize);
  $height = imagesy($fullsize);
  if ($width > $height){
    $scale = $target/$width;
  }
  else{
    $scale = $target/$height;
  }
  if ($scale < 1){
    $w = round($scale * $width);
    $h = round($scale * $height);
    $thumbnail = imagecreatetruecolor($w, $h);
    imagecopyresized($thumbnail, $fullsize, 0, 0, 0, 0, $w, $h, $width,
$height);
    header("Content-type: image/jpeg");
    imagejpeg($thumbnail);
  }
  else{
    imagejpeg($fullsize);
  }
?>

So for 50x50 images, I just use:
http://example.com/scale.php/full/path/to/originalfile.jpg

If I want some other size, I just use:
http://example.com/scale.php/target/150/full/path/to/originalfile.jpg

where 150 is the max width/height I want.

> I wanted to find something that would work for only GIF and JPG image
> types.

Looks like I just output a JPEG no matter what the input is -- You'll have
to add another 'switch' statement much like the one near the top to decide
which kind of image to output.

Probably be a good idea to add some error-checking right after the
getimagesize call, and if that failed, just die().

-- 
Like Music?
http://l-i-e.com/artists.htm

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux