Skip to content

Instantly share code, notes, and snippets.

@florentdestremau
Created March 17, 2015 20:58
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 florentdestremau/3cb264ed66e51f3e7ae2 to your computer and use it in GitHub Desktop.
Save florentdestremau/3cb264ed66e51f3e7ae2 to your computer and use it in GitHub Desktop.
Make an automatic thumbnail in PHP
function create_thumb($src,$dest,$desired_width = false, $desired_height = false)
{
/*If no dimenstion for thumbnail given, return false */
if (!$desired_height&&!$desired_width) return false;
$fparts = pathinfo($src);
$ext = strtolower($fparts['extension']);
/* if its not an image return false */
if (!in_array($ext,array('gif','jpg','png','jpeg'))) return false;
/* read the source image */
if ($ext == 'gif')
$resource = imagecreatefromgif($src);
else if ($ext == 'png')
$resource = imagecreatefrompng($src);
else if ($ext == 'jpg' || $ext == 'jpeg')
$resource = imagecreatefromjpeg($src);
$width = imagesx($source_image);
$height = imagesy($source_image);
/* find the "desired height" or "desired width" of this thumbnail, relative to each other, if one of them is not given */
if(!$desired_height) $desired_height = floor($height*($desired_width/$width));
if(!$desired_width) $desired_width = floor($width*($desired_height/$height));
/* create a new, "virtual" image */
$virtual_image = imagecreatetruecolor($desired_width,$desired_height);
/* copy source image at a resized size */
imagecopyresized($virtual_image,$resource,0,0,0,0,$desired_width,$desired_height,$width,$height);
/* create the physical thumbnail image to its destination */
/* Use correct function based on the desired image type from $dest thumbnail source */
$fparts = pathinfo($dest);
$ext = strtolower($fparts['extension']);
/* if dest is not an image type, default to jpg */
if (!in_array($ext,array('gif','jpg','png','jpeg'))) $ext = 'jpg';
$dest = $fparts['dirname'].'/'.$fparts['filename'].'.'.$ext;
if ($ext == 'gif')
imagegif($virtual_image,$dest);
else if ($ext == 'png')
imagepng($virtual_image,$dest,1);
else if ($ext == 'jpg' || $ext == 'jpeg')
imagejpeg($virtual_image,$dest,100);
return array(
'width' => $width,
'height' => $height,
'new_width' => $desired_width,
'new_height'=> $desired_height,
'dest' => $dest
);
}
@florentdestremau
Copy link
Author

Not mine at the start, I just thought it might be useful to have it written down somewhere

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment