Skip to content

Instantly share code, notes, and snippets.

@bearlikelion
Created September 27, 2013 16:31
Show Gist options
  • Save bearlikelion/6731285 to your computer and use it in GitHub Desktop.
Save bearlikelion/6731285 to your computer and use it in GitHub Desktop.
Slothy.me Image Controller
<?php
class ImageController {
protected function selectRandom()
{
if (Cache::has('sloths'))
{
$sloths = Cache::get('sloths');
if (count($sloths) > 1) return $sloths;
else
{
Cache::forget('sloths');
$files = glob(public_path() . '/assets/images/*.jpg');
Cache::put('sloths', $files, 720);
return $files;
}
}
else
{
$files = glob(public_path() . '/assets/images/*.jpg');
Cache::put('sloths', $files, 720);
return $files;
}
}
public function getRandom()
{
$files = self::selectRandom();
array_shift($files);
Cache::put('sloths', $files, 240);
return $files[0];
}
public function getSquare($size)
{
if (intval($size) == 0) App::abort(404, 'Non-numerical value passed');
else
{
if (Cache::has($size)) $image = Cache::get($size);
else
{
$image['img'] = self::getRandom();
$image['timestamp'] = date ("F d Y H:i:s GMT");
Cache::put($size, array('img' => $image['img'], 'timestamp' => $image['timestamp']), 240);
}
$dimensions = getimagesize($image['img']);
$source = imagecreatefromjpeg($image['img']);
$placeholder = imagecreatetruecolor($size, $size);
imagecopyresampled($placeholder, $source, 0, 0, 0, 0, $size, $size, $dimensions[0], $dimensions[1]);
imagedestroy($source);
return Response::make(View::make('image', array('img' => $placeholder)), 200, array('Content-Type' => 'image/jpeg', 'Cache-Control' => 'max-age=14400', 'Last-Modified' => $image['timestamp']));
}
}
public function getImage($width, $height)
{
if (intval($width) == 0 || intval($height) == 0) App::abort(404, 'Non-numerical value passed');
else
{
if (Cache::has($width.'x'.$height)) $image = Cache::get($width.'x'.$height);
else
{
$image['img'] = self::getRandom();
$image['timestamp'] = date ("F d Y H:i:s GMT");
Cache::put($width.'x'.$height, array('img' => $image['img'], 'timestamp' => $image['timestamp']), 240);
}
$dimensions = getimagesize($image['img']);
$source = imagecreatefromjpeg($image['img']);
$placeholder = imagecreatetruecolor($width, $height);
imagecopyresampled($placeholder, $source, 0, 0, 0, 0, $width, $height, $dimensions[0], $dimensions[1]);
imagedestroy($source);
return Response::make(View::make('image', array('img' => $placeholder)), 200, array('Content-Type' => 'image/jpeg', 'Cache-Control' => 'max-age=14400', 'Last-Modified' => $image['timestamp']));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment