Skip to content

Instantly share code, notes, and snippets.

@Dragory
Created May 20, 2013 12:01
Show Gist options
  • Save Dragory/5611835 to your computer and use it in GitHub Desktop.
Save Dragory/5611835 to your computer and use it in GitHub Desktop.
<?php
namespace Services\Mivir;
class Thumbnailer
{
public function thumbnailify($path, $width, $height)
{
if ( ! file_exists($path)) {
throw new \Exception('The file to thumbnailify does not exist.');
}
$image = imagecreatefromstring(file_get_contents($path));
$image = $this->cutToAspectRatio($image, ($width/$height));
$image = $this->resize($image, $width, $height);
return $image;
}
protected function cutToAspectRatio($res, $hRatio)
{
$origWidth = imagesx($res);
$origHeight = imagesy($res);
$vRatio = 1 / $hRatio;
$width = $origWidth;
$height = $vRatio * $origWidth;
if ($height > $origHeight) {
$height = $origHeight;
$width = $hRatio * $height;
}
$dest = imagecreatetruecolor($width, $height);
imagecopy($dest, $res, 0, 0, 0, 0, $width, $height);
return $dest;
}
protected function resize($res, $width, $height)
{
$dest = imagecreatetruecolor($width, $height);
imagecopyresized($dest, $res, 0, 0, 0, 0, $width, $height, imagesx($res), imagesy($res));
return $dest;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment