Skip to content

Instantly share code, notes, and snippets.

@sp3c73r2038
Created June 4, 2012 03:47
Show Gist options
  • Save sp3c73r2038/2866219 to your computer and use it in GitHub Desktop.
Save sp3c73r2038/2866219 to your computer and use it in GitHub Desktop.
crop_image in gd equivalent to cropImage in imagick
<?php
function cropImage ($image, $width, $height, $x, $y) {
list($w, $h) = getimagesize($image);
$nw = (($width + $x) >= $w) ? $w - $x : $width;
$nh = (($height + $y) >= $h) ? $h - $y : $height;
// var_dump($nw);
// var_dump($nh);
if ($nw == 0 || $nh == 0) {
throw new Exception ('cannot crop image, dst image\'s width or height is 0!');
}
$src = imagecreatefromjpeg($image);
$dst = imagecreatetruecolor($nw, $nh);
imagecopyresampled($dst, $src, 0, 0, $x, $y, $nw, $nh, $nw, $nh);
return $dst;
}
$gd = cropImage('saya.jpg', 1600, 1200, 1200, 900);
imagejpeg($gd);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment