Skip to content

Instantly share code, notes, and snippets.

@robballou
Created April 3, 2009 21:12
Show Gist options
  • Save robballou/89974 to your computer and use it in GitHub Desktop.
Save robballou/89974 to your computer and use it in GitHub Desktop.
<?php
public function resize($new_w, $new_h, $preserve=false){
$name = $this->image;
$e = $this->getExtension();
$filename = dirname($this->image) .'/'. $e['file'] .'_'. $new_w .'x'. $new_h . $e['extension'];
// this function only works if the imagecreatefromjpeg function exists
if(!function_exists('imagecreatefromjpeg')){ return false; }
// adapted from http://icant.co.uk/articles/phpthumbnails/
$system=explode(".",$name);
$len = count($system) - 1;
if (preg_match("/jpg|jpeg/",$system[$len])){$src_img=imagecreatefromjpeg($name);}
if (preg_match("/png/",$system[$len])){$src_img=imagecreatefrompng($name);}
$old_x=imageSX($src_img);
$old_y=imageSY($src_img);
if ($old_x > $old_y){
$thumb_w=$new_w;
$thumb_h=$old_y*($new_h/$old_x);
}
if ($old_x < $old_y){
$thumb_w=$old_x*($new_w/$old_y);
$thumb_h=$new_h;
}
if ($old_x == $old_y){
$thumb_w=$new_w;
$thumb_h=$new_h;
}
$dst_img = ImageCreateTrueColor($thumb_w,$thumb_h);
imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $thumb_w, $thumb_h, $old_x, $old_y);
if(preg_match("/png/",$system[1])){
imagepng($dst_img, $filename);
}
else {
imagejpeg($dst_img, $filename);
}
imagedestroy($dst_img);
imagedestroy($src_img);
// end adapted code
if(!$preserve){
// we should replace the current image
if(file_exists($this->image)){
unlink($this->image);
}
$this->image = $filename;
}
if(!file_exists($filename)){
throw new Exception("Image::resize() failed to create the file `$filename`");
}
return $filename;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment