Skip to content

Instantly share code, notes, and snippets.

@joshuamilford
Created July 11, 2011 17:29
Show Gist options
  • Save joshuamilford/1076339 to your computer and use it in GitHub Desktop.
Save joshuamilford/1076339 to your computer and use it in GitHub Desktop.
PHP Image Resizer
function resize($incoming, $max_width, $max_height, $crop = true){
$original_name = explode('.', $incoming);
$original_ext = strtolower(array_pop($original_name));
$original_name = implode('.', $original_name);
if(!file_exists($incoming)) $error = 'Original file doesn\'t exist.';
else{
if(!$original_info = getimagesize($incoming)) $error = 'Original file isn\'t a valid image.';
else{
$original_width = $original_info[0];
$original_height = $original_info[1];
switch($original_ext){
case 'jpg' :
case 'jpeg';
$original = imagecreatefromjpeg($incoming);
break;
case 'png';
$original = imagecreatefrompng($incoming);
break;
case 'gif';
$original = imagecreatefromgif($incoming);
break;
}
if(!$original) $error = 'Invalid format.';
else{
$original = imagecreatefromjpeg($incoming);
$x = 0;
$y = 0;
if($max_width == 0) $max_width = ($max_height / $original_height) * $original_width;
if($max_height == 0) $max_height = ($max_width / $original_width) * $original_height;
$new_width = $max_width;
$new_height = ($max_width / $original_width) * $original_height;
if($crop){
if($new_height < $max_height){
$new_height = $max_height;
$new_width = ($max_height / $original_height) * $original_width;
}
$x = ($max_width / 2) - ($new_width / 2);
$y = ($max_height / 2) - ($new_height / 2);
$temp = imagecreatetruecolor($max_width, $max_height);
}
else{
if($new_height > $max_height){
$new_height = $max_height;
$new_width = ($max_height / $original_height) * $original_width;
}
$temp = imagecreatetruecolor($new_width, $new_height);
}
imagecopyresampled($temp, $original, $x, $y, 0, 0, $new_width, $new_height, $original_width, $original_height);
switch($original_ext){
case 'jpg' :
case 'jpeg';
imagejpeg($temp, $original_name . '_small.' . $original_ext, 100);
break;
case 'png';
imagepng($temp, $original_name . '_small.' . $original_ext);
break;
case 'gif';
imagegif($temp, $original_name . '_small.' . $original_ext);
break;
}
imagedestroy($original);
imagedestroy($temp);
return $original_name . '_small.' . $original_ext;
}
}
}
die($error);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment