Created
May 20, 2013 12:01
-
-
Save Dragory/5611835 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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