Skip to content

Instantly share code, notes, and snippets.

@321zeno
Last active August 29, 2015 14:22
Show Gist options
  • Save 321zeno/57854784e3fb0cce9c2a to your computer and use it in GitHub Desktop.
Save 321zeno/57854784e3fb0cce9c2a to your computer and use it in GitHub Desktop.
Resize images on the fly
<?php
class ImageResizeController extends BaseController {
/**
* This method catches urls like /imagecache/width/height/path/to/original_image.jpg and
* creates the image if public/imagecache/width/height/path/to/original_image.jpg doesn't exist.
*
* Urls like this are used for returning a resized version of /path/to/original_image.jpg
*
* Requires "intervention/image": "~2.1"
*/
public function display($width, $height = null, $path = null) {
if (!$path)
{
$path = $height;
$height = null;
$savePathConfig = [
'folder' => 'imagecache',
'width' => $width,
'path' => dirname($path),
'filename' => basename($path),
];
} else {
$savePathConfig = [
'folder' => 'imagecache',
'width' => $width,
'height' => $height,
'path' => dirname($path),
'filename' => basename($path),
];
}
//build cache path
$cachePath = implode('/',$savePathConfig);
$cachePath = public_path($cachePath);
//if cached version already exists, return cached version
if (File::exists($cachePath)) {
$image = Image::make($cachePath);
return $image->response();
}
//generate cached version
if (File::exists(public_path($path))) {
$readPath = public_path($path);
$image = Image::make($readPath);
if ($height) {
$image->fit($width, $height);
} else {
// $image->resize($width, null);
$image->resize($width, null, function ($constraint) {
$constraint->aspectRatio();
});
}
// $image->sharpen(5);
$saveFolder = dirname($cachePath);
//create folder
@mkdir($saveFolder, 0755, true);
$image->save($cachePath, 75);
return $image->response();
} else {
return 'error no file';
}
}
}
<?php
Route::get('/imagecache/{width}/{height}/{path}', array('as' => 'image', 'uses' => 'ImageResizeController@display'))
->where(['width' => '[0-9]+', 'height' => '[0-9]+', 'path' => '([A-z\d-\s\/_.]+)?']);
Route::get('/imagecache/{width}/{path}', array('as' => 'image', 'uses' => 'ImageResizeController@display'))
->where(['width' => '[0-9]+', 'path' => '([A-z\d-\s\/_.]+)?']);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment