Skip to content

Instantly share code, notes, and snippets.

@evaldas-raisutis
Created October 21, 2013 20:36
Show Gist options
  • Save evaldas-raisutis/7090530 to your computer and use it in GitHub Desktop.
Save evaldas-raisutis/7090530 to your computer and use it in GitHub Desktop.
A class for creating image thumbnail
class thumbnail {
public $path;
public $save;
public $width;
public $height;
public function __construct($path, $save, $width, $height) {
$this->path = $path; // path to original image to create thumbnail from
$this->save = $save; // path and file name for saving a thumbnail
$this->width = $width; // desired width of the thumbnail
$this->height = $height; // desired height of the thumbnail
}
public function create_thumbnail() {
$info = getimagesize($path);
$size = array($info[0], $info[1]);
if($info['mime'] == "image/png")
{
$src = imagecreatefrompng($path);
}
else if ($info['mime'] == "image/jpeg")
{
$src = imagecreatefromjpeg($path);
}
else if ($info['mime'] == "image/gif")
{
$src = imagecreatefromgif($path);
}
else
{
return false;
}
$thumb = imagecreatetruecolor($width, $height);
$src_aspect = $size[0] / $size[1];
$thumb_aspect = $width / $height;
if($src_aspect < $thumb_aspect)
{
$scale = $width / $size[0];
$new_size = array($width, $width / $src_aspect);
$src_pos = array(0, ($size[1] * $scale - $height) / $scale / 2);
}
else if($src_aspect > $thumb_aspect)
{
$scale = $height / $size[1];
$new_size = array($height * $src_aspect, $height);
$src_pos = array(($size[0] * $scale - $width) / $scale / 2, 0);
}
else
{
$new_size = array($width, $height);
$src_pos = array(0, 0);
}
$new_size[0] = max($new_size[0], 1);
$new_size[1] = max($new_size[1], 1);
imagecopyresampled($thumb, $src, 0, 0, $src_pos[0], $src_pos[1], $new_size[0], $new_size[1], $size[0], $size[1]);
if($save === false)
{
if($info['mime'] == "image/png")
{
return imagepng($thumb);
}
else if ($info['mime'] == "image/jpeg")
{
return imagejpeg($thumb);
}
else if ($info['mime'] == "image/gif")
{
return imagegif($thumb);
}
}
else
{
if($info['mime'] == "image/png")
{
return imagepng($thumb, $save);
}
else if ($info['mime'] == "image/jpeg")
{
return imagejpeg($thumb, $save);
}
else if ($info['mime'] == "image/gif")
{
return imagegif($thumb, $save);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment