Skip to content

Instantly share code, notes, and snippets.

@gentritabazi
Last active June 10, 2020 11:18
Show Gist options
  • Save gentritabazi/e80fe3740920d41a45d8e1960e7bed90 to your computer and use it in GitHub Desktop.
Save gentritabazi/e80fe3740920d41a45d8e1960e7bed90 to your computer and use it in GitHub Desktop.
function create_thumbnail($max_width, $max_height, $source_file, $dst_dir)
{
$imgsize = getimagesize($source_file);
$width = $imgsize[0];
$height = $imgsize[1];
$mime = $imgsize['mime'];
switch ($mime) {
case 'image/png':
$image_create = 'imagecreatefrompng';
$image = 'imagepng';
$quality = 9;
break;
case 'image/jpeg':
$image_create = 'imagecreatefromjpeg';
$image = 'imagejpeg';
$quality = 100;
break;
default:
return false;
break;
}
$dst_img = imagecreatetruecolor($max_width, $max_height);
imagealphablending($dst_img, false);
imagesavealpha($dst_img, true);
$src_img = $image_create($source_file);
$width_new = $height * $max_width / $max_height;
$height_new = $width * $max_height / $max_width;
// If the new width is greater than the actual width of the image, then the height is too large and the rest cut off, or vice versa
if ($width_new > $width) {
// Cut point by height
$h_point = (($height - $height_new) / 2);
// Copy image
imagecopyresampled($dst_img, $src_img, 0, 0, 0, $h_point, $max_width, $max_height, $width, $height_new);
} else {
// Cut point by width
$w_point = (($width - $width_new) / 2);
imagecopyresampled($dst_img, $src_img, 0, 0, $w_point, 0, $max_width, $max_height, $width_new, $height);
}
$image($dst_img, $dst_dir, $quality);
if ($dst_img) {
imagedestroy($dst_img);
}
if ($src_img) {
imagedestroy($src_img);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment