Last active
November 28, 2017 03:59
-
-
Save eimg/78690e9a6cc0e062324d0c7030839002 to your computer and use it in GitHub Desktop.
Create image thumb on given size without effection original aspect ratio
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function generate_thumb($source_image_path, $thumbnail_image_path, $result_width, $result_height) { | |
if(!file_exists($source_image_path)) { | |
return false; | |
} | |
if(!getimagesize($source_image_path)) { | |
return false;; | |
} | |
list( | |
$source_image_width, | |
$source_image_height, | |
$source_image_type | |
) = getimagesize($source_image_path); | |
switch ($source_image_type) { | |
case IMAGETYPE_GIF: | |
$source_gd_image = imagecreatefromgif($source_image_path); | |
break; | |
case IMAGETYPE_JPEG: | |
$source_gd_image = imagecreatefromjpeg($source_image_path); | |
break; | |
case IMAGETYPE_PNG: | |
$source_gd_image = imagecreatefrompng($source_image_path); | |
break; | |
default: | |
return false; | |
} | |
$source_aspect_ratio = $source_image_width / $source_image_height; | |
$thumbnail_aspect_ratio = $result_width / $result_height; | |
if ($source_image_width <= $result_width && | |
$source_image_height <= $result_height) { | |
$thumbnail_image_width = $source_image_width; | |
$thumbnail_image_height = $source_image_height; | |
} elseif ($thumbnail_aspect_ratio > $source_aspect_ratio) { | |
$thumbnail_image_width = (int) ($result_height * $source_aspect_ratio); | |
$thumbnail_image_height = $result_height; | |
} else { | |
$thumbnail_image_width = $result_width; | |
$thumbnail_image_height = (int) ($result_width / $source_aspect_ratio); | |
} | |
$thumbnail_gd_image = imagecreatetruecolor($thumbnail_image_width, $thumbnail_image_height); | |
imagecopyresampled($thumbnail_gd_image, $source_gd_image, 0, 0, 0, 0, $thumbnail_image_width, $thumbnail_image_height, $source_image_width, $source_image_height); | |
imagejpeg($thumbnail_gd_image, $thumbnail_image_path, 90); | |
imagedestroy($source_gd_image); | |
imagedestroy($thumbnail_gd_image); | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment