【问题标题】:How could I cache images using Laravel如何使用 Laravel 缓存图像
【发布时间】:2018-12-15 09:13:29
【问题描述】:

我想在 Laravel 中缓存图像。我能找到的所有解决方案都可以找到我为自己服务的图像,但这些图像来自 google places api 调用。从地点详细信息 api 调用。

因此,如果用户使用我的 web 应用程序请求某个位置的图像,我想缓存作为结果检索到的图像。

google places details api 调用检索图像的哈希值,我可以像这样构造图像的 url:

$photos[] = 'https://maps.googleapis.com/maps/api/place/photo?photoreference=' . 
             $photo->photo_reference . 
            '&sensor=false&maxheight=400&maxwidth=400&key=' . 
             $apiKey;

然后检索图像并在前端显示。

我们通过像Cache::get($id.'photos') 这样的方式使用 Laravel 方式,但这只会缓存 url,这不是很有帮助。

我们还找到了以下链接https://github.com/Intervention/imagecache,但是这个 repo 已经很老了,我们使用的是 Laravel 5.7,所以这个 repo 中使用的技术不再适用。

任何建议将不胜感激!

【问题讨论】:

  • 这是一个旧的 repo,因为它不是那种需要定期更新的东西——“这个 repo 中采用的技术”仍然在很大程度上适用。在你解雇它之前试一试。

标签: php laravel laravel-5 google-places-api


【解决方案1】:

如果您可以直接从该 URL 下载实际图像,那么您可以这样:

用户在您的 URL yourdomain.com/your-api/image/{reference} 上请求图片

  • 尝试从缓存中获取图片(通过 URL),如果存在则返回
  • 否则,请将图片下载到您的storage 文件夹之一
  • 通过 URL 缓存图片
  • 返回图片的本地缓存副本
  • 您可能还想创建一个命令,从该存储文件夹中删除旧图像

可能是这样的(未经测试)

/** @return \Illuminate\Http\Response */
function getImage($reference) {
    $imageUrl = buildImageUrl($reference);
    $hash = getHash($imageUrl);
    if($location = Cache::get("image-$hash")) {
        if(file_exists($location)) {
            return response()->file($location);
        }
    }

    $location = cacheImage($imageUrl, $hash);
    return response()->file($location);
}

function cacheImage($imageUrl, $hash) {
    $hash = getHash($imageUrl);
    $location = storage_path("images/$hash");

    // download the image and cache its filename by hash
    $image = downloadImage($imageUrl, $location);
    file_put_contents($location, $image);
    Cache::put("image-$hash", $location);

    return $location;
}

function getHash($string) {
    return sha1($string);
}

【讨论】:

    猜你喜欢
    • 2020-04-03
    • 2020-08-16
    • 2016-12-08
    • 1970-01-01
    • 2020-10-08
    • 2020-10-18
    • 2013-12-25
    • 2014-11-06
    • 2015-03-25
    相关资源
    最近更新 更多