Skip to content

Instantly share code, notes, and snippets.

@dennisdegryse
Last active August 29, 2015 14:13
Show Gist options
  • Select an option

  • Save dennisdegryse/8b3dad941bacfe5653e2 to your computer and use it in GitHub Desktop.

Select an option

Save dennisdegryse/8b3dad941bacfe5653e2 to your computer and use it in GitHub Desktop.
Scaling and cropping an image to the specified size using PHP GD
<?php
/**
* Loads an image into a GD resource and scales/crops it to the given target size.
*
* @param string $filename The file name of the image.
* @param string $mime The mime type of the image.
* @param string $target_size The target size.
*
* @throws Exception When the image MimeType is invalid.
*
* @return resource The GD image resource.
*
* @author Dennis Degryse
*/
imagescalecrop($filename, $mime, $target_size) {
// validate the mime type
$valid_formats = ['jpeg', 'gif', 'png', 'bmp', 'wbmp', 'webp', 'xbm'];
list($mime_type, $mime_format) = expode('/', $mime);
if ($mime_type !== 'image' || !in_array($mime_format) {
throw new \Exception('Invalid image.');
}
$img = call_user_func("imagecreatefrom$mime_format", $filename);
$factor = max(array_map(function($td, $d) { return $td / $d; }, $target_size, $size = imagegetsize($filename)));
$new_size = array_map(function($d) use($factor) { return $d * $factor; }, $size);
$offset = array_map(function($d, $td) { return ($d - $td) / 2}, $new_size);
imagescale($img, $new_size[0], $new_size[1]);
imagecrop($img, [ $offset[0], $offset[1], $target_size[0], $target_size[1] ]);
return $img;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment