Skip to content

Instantly share code, notes, and snippets.

@joni
Created January 28, 2012 21:16
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save joni/1695782 to your computer and use it in GitHub Desktop.
Resize and crop an image in PHP and GD
<?php
$srcPath = "your source image path goes here";
$dstPath = "your destination image path goes here";
$size = "90x90";
list($w, $h, $type) = getimagesize($srcPath);
switch ($type) {
case IMAGETYPE_JPEG:
$src = imagecreatefromjpeg($srcPath);
break;
case IMAGETYPE_PNG:
$src = imagecreatefrompng($srcPath);
break;
case IMAGETYPE_GIF:
$src = imagecreatefromgif($srcPath);
break;
case IMAGETYPE_BMP:
$src = imagecreatefrombmp($srcPath);
break;
}
list($dst_w, $dst_h) = explode('x', $size);
$dst = imagecreatetruecolor($dst_w, $dst_h);
$dst_x = $dst_y = 0;
$src_x = $src_y = 0;
if ($dst_w/$dst_h < $w/$h) {
$src_w = $h*($dst_w/$dst_h);
$src_h = $h;
$src_x = ($w-$src_w)/2;
$src_y = 0;
} else {
$src_w = $w;
$src_h = $w*($dst_h/$dst_w);
$src_x = 0;
$src_y = ($h-$src_h)/2;
}
imagecopyresampled($dst, $src, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
imagejpeg($dst, $dstPath);
imagedestroy($src);
imagedestroy($dst);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment