如何在 Laravel 中缓存来自 url 的图像
How to cache images from url in Laravel
我有一个 Laravel 4 应用程序显示来自位于远程服务器上的另一个 PHP 应用程序的图像。
我想知道在本地 Laravel 应用程序上缓存来自远程服务器的图像的最佳解决方案是什么。
请注意,几乎不可能从远程服务器copy/past整个图像目录,因为有超过 150k 个图像定期更新(每分钟) 并且也存在数据库相关性(文件名与数据库中的列值)。
我正要使用 Rsync
来同步两个目录(远距离和本地),但我还需要在显示它们之前调整图像的大小,并以不同于在上的方式组织图像子目录远程服务器。
首先,我在 Laravel 上安装了 Intervention Image Class 软件包,并创建了一个 Route
:
Route::get('photos/item/{size}/{reference}/{photo}', 'ImgController@showImg');
并且在 ImgController
中:
public function showImg( $size, $reference, $photo )
{
switch ( $size ) {
case '300x225':
$jpg = Image::make( 'http://myremoteapp.com/uploads/' . $reference . '/' . $photo )->resize( 300, 225 )->response( 'jpg' );
break;
}
return $jpg;
}
这可行,但它不会将图像保留在浏览器的缓存中,而且还会产生性能问题,因为每次打开页面时都必须下载图像并调整其大小。
我听说过 Intervention Image Cache,但我不确定它是否适用于从 URL 获取的图像。
任何关于如何以适当方式解决此问题的意见和建议将不胜感激。
您可以将缓存路由用作:
Route::filter('cache', function($route, $request, $response = null) {
$key = 'route-' . safe_title(URL::full());
if( is_null($response) && Cache::has($key) ) {
return Cache::get($key);
} elseif( !is_null($response) && !Cache::has($key) ) {
// Code this here
Cache::put($key, $response->getContent(), 30);
}
});
Route::group(array( 'before' => 'cache', 'after' => 'cache' ), function() {
Route::get('photos/item/{size}/{reference}/{photo}', 'ImgController@showImg');
});
注意:
Route::filter() 已从 Laravel 中删除,因为 > 5.0
我有一个 Laravel 4 应用程序显示来自位于远程服务器上的另一个 PHP 应用程序的图像。
我想知道在本地 Laravel 应用程序上缓存来自远程服务器的图像的最佳解决方案是什么。
请注意,几乎不可能从远程服务器copy/past整个图像目录,因为有超过 150k 个图像定期更新(每分钟) 并且也存在数据库相关性(文件名与数据库中的列值)。
我正要使用 Rsync
来同步两个目录(远距离和本地),但我还需要在显示它们之前调整图像的大小,并以不同于在上的方式组织图像子目录远程服务器。
首先,我在 Laravel 上安装了 Intervention Image Class 软件包,并创建了一个 Route
:
Route::get('photos/item/{size}/{reference}/{photo}', 'ImgController@showImg');
并且在 ImgController
中:
public function showImg( $size, $reference, $photo )
{
switch ( $size ) {
case '300x225':
$jpg = Image::make( 'http://myremoteapp.com/uploads/' . $reference . '/' . $photo )->resize( 300, 225 )->response( 'jpg' );
break;
}
return $jpg;
}
这可行,但它不会将图像保留在浏览器的缓存中,而且还会产生性能问题,因为每次打开页面时都必须下载图像并调整其大小。
我听说过 Intervention Image Cache,但我不确定它是否适用于从 URL 获取的图像。
任何关于如何以适当方式解决此问题的意见和建议将不胜感激。
您可以将缓存路由用作:
Route::filter('cache', function($route, $request, $response = null) {
$key = 'route-' . safe_title(URL::full());
if( is_null($response) && Cache::has($key) ) {
return Cache::get($key);
} elseif( !is_null($response) && !Cache::has($key) ) {
// Code this here
Cache::put($key, $response->getContent(), 30);
}
});
Route::group(array( 'before' => 'cache', 'after' => 'cache' ), function() {
Route::get('photos/item/{size}/{reference}/{photo}', 'ImgController@showImg');
});
注意: Route::filter() 已从 Laravel 中删除,因为 > 5.0