Skip to content

Instantly share code, notes, and snippets.

@nicksheffield
Created March 16, 2012 00:04
Show Gist options
  • Save nicksheffield/2047763 to your computer and use it in GitHub Desktop.
Save nicksheffield/2047763 to your computer and use it in GitHub Desktop.
Smart thumbnail generation
<?php
/*
Really useful for echoing with CI
*/
function generate_thumbnail($filename, $thumb_width, $thumb_height){
$path = 'uploads/'.$filename;
if(strstr($filename, 'jpg')){
$image = imagecreatefromjpeg($path);
}elseif(strstr($filename, 'png')){
$image = imagecreatefrompng($path);
}else{
$image = imagecreatefromgif($path);
}
$width = imagesx($image);
$height = imagesy($image);
$original_aspect = $width / $height;
$thumb_aspect = $thumb_width / $thumb_height;
if($original_aspect >= $thumb_aspect){
// If image is wider than thumbnail (in aspect ratio sense)
$new_height = $thumb_height;
$new_width = $width / ($height / $thumb_height);
}else{
// If the thumbnail is wider than the image
$new_width = $thumb_width;
$new_height = $height / ($width / $thumb_width);
}
$thumb = imagecreatetruecolor($thumb_width, $thumb_height);
// Resize and crop
imagecopyresampled($thumb,
$image,
0 - ($new_width - $thumb_width) / 2,
0 - ($new_height - $thumb_height) / 2,
0, 0,
$new_width, $new_height,
$width, $height
);
return $thumb;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment