Skip to content

Instantly share code, notes, and snippets.

@abronte
Created October 5, 2010 02:21
Show Gist options
  • Select an option

  • Save abronte/610857 to your computer and use it in GitHub Desktop.

Select an option

Save abronte/610857 to your computer and use it in GitHub Desktop.
PHP image crop resize
//if the image if taller than wide, resize W to desired length then crop the top and bottom to fit
if($image_w < $image_h) {
$tmp_h=$image_h*($new_h/$image_w);
$tmp_big = imagecreatetruecolor($new_w, $tmp_h);
$tmp = imagecreatetruecolor($new_w, $new_h);
$diff = ($tmp_h - $new_h)/2;
imagecopyresampled($tmp_big,$image,0,0,0,$diff,$new_w,$tmp_h,$image_w,$image_h);
imagecopyresampled($tmp,$tmp_big,0,0,0,$diff,$new_w,$new_h,$new_w,$new_h);
imagedestroy($tmp_big);
//if the image if wider than tall, resize H to desired length then crop the left and right to fit
} elseif($image_w > $image_h) {
$tmp_w=$image_w*($new_w/$image_h);
$tmp_big = imagecreatetruecolor($tmp_w, $new_h);
$tmp = imagecreatetruecolor($new_w, $new_h);
$diff = ($tmp_w - $new_w)/2;
imagecopyresampled($tmp_big,$image,0,0,0,0,$tmp_w,$new_h,$image_w,$image_h);
imagecopyresampled($tmp,$tmp_big,0,0,$diff,0,$new_w,$new_h,$new_w,$new_h);
imagedestroy($tmp_big);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment