Last active
December 22, 2015 00:48
-
-
Save sam0x17/6391591 to your computer and use it in GitHub Desktop.
The Ultimate Smart Image Re-sizing Routine. You provide the original image, and a desired width and/or height. This function will intelligently re-size the original image to fit, centered, within the specified dimensions. Either width or height can be omitted to have the re-size "lock" only on width or height. Fantastic for thumbnail generation.…
This file contains 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
<? | |
function smart_img_resize($orig, $dest_width=null, $dest_height=null) | |
{ | |
$orig_width = imagesx($orig); | |
$orig_height = imagesy($orig); | |
$vertical_offset = 0; | |
$horizontal_offset = 0; | |
if($dest_width == null) | |
{ | |
if($dest_height == null) | |
{ | |
die('$dest_width and $dest_height cannot both be null!'); | |
} | |
// height is locked | |
$dest_width = $dest_height * $orig_width / $orig_height; | |
} else { | |
if($dest_height == null) | |
{ | |
// width is locked | |
$dest_height = $dest_width * $orig_height / $orig_width; | |
} else { | |
// both dimensions are locked | |
$vertical_offset = $dest_height - ($orig_height * $dest_width) / $orig_width; | |
$horizontal_offset = $dest_width - ($dest_height * $orig_width) / $orig_height; | |
if($vertical_offset < 0) $vertical_offset = 0; | |
if($horizontal_offset < 0) $horizontal_offset = 0; | |
} | |
} | |
$img = imagecreatetruecolor($dest_width, $dest_height); | |
imagesavealpha($img, true); | |
imagealphablending($img, false); | |
$transparent = imagecolorallocatealpha($img, 0, 0, 0, 127); | |
imagefill($img, 0, 0, $transparent); | |
imagecopyresampled($img, $orig, round($horizontal_offset / 2), | |
round($vertical_offset / 2), | |
0, | |
0, | |
round($dest_width - $horizontal_offset), | |
round($dest_height - $vertical_offset), | |
$orig_width, | |
$orig_height); | |
return $img; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment