Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robmorgan/450803 to your computer and use it in GitHub Desktop.
Save robmorgan/450803 to your computer and use it in GitHub Desktop.
<?php
/**
* Creates a thumbnail for any type of pre-existing image. Always saves as PNG image
* Works properly with GIF transparency and PNG Alpha Transparency.
* If Image is less than max_width and max_height it will stay at the size of the image.
*
* @param string - The location of the pre-existing image.
* @param string - The location to save the thumbnail, including filename and extension.
* @param int - The Maximum Width, Default of 150
* @param int - The Maximum Height, Default of 150
* @return bool - Success of saving the thumbnail.
*/
function imagecreatethumbnail($file,$output,$max_width = 150,$max_height = 150)
{
$img = imagecreatefromstring(file_get_contents($file));
list($width, $height, $type, $attr) = getimagesize($file);
if($height > $max_height || $width > $max_width)
{
if($width > $height) { $thumb_width = $max_width; $thumb_height = ceil(($height * $thumb_width)/$width); }
else { $thumb_height = $max_height; $thumb_width = ceil(($width * $thumb_height)/$height); }
} else {
$thumb_width = $width;
$thumb_height = $height;
}
imagesavealpha($img,true);
$thumb = imagecreatetruecolor($thumb_width,$thumb_height);
imagesavealpha($thumb,true);
imagealphablending($thumb,false);
imagecopyresampled($thumb,$img,0,0,0,0,$thumb_width,$thumb_height,$width,$height);
$return = imagepng($thumb,$output);
imagedestroy($img);
imagedestroy($thumb);
return $return;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment