Laravel Azure Blob存储缓存映像

时间:2020-06-18 07:57:33

标签: php laravel image azure caching

这是我的情况: 我有一个Laravel 6.x应用程序,并且正在使用FlySystemAzureBlobStorage包将图像存储在Azure Blob存储上。 然后,我想使用InterventionImageCache包来获取并缓存图像,以便更快地以不同大小下载客户端。 我已经用这种方式做到了:

public static function getImageResponseForApi($storageDiskName, $imagePath, $width = null, $height = null)
{
    //check if the image exists on disk
    $exists = empty($storageDiskName) ?
        Storage::exists($imagePath) :
        Storage::disk($storageDiskName)->exists($imagePath);
    if ($exists) {
        $image = empty($storageDiskName) ?
            Storage::get($imagePath) :
            Storage::disk($storageDiskName)->get($imagePath);
        if (!empty($width) || !empty($height)) {
            //use the image cache function to get the cached image if exists
            $image = \Image::cache(function ($ima) use ($image, $width, $height) {
                //check if height and with are higher than original or not
                $ima->make($image)->resize($width, $height, function ($constraint) {
                    $constraint->aspectRatio();
                    $constraint->upsize();
                });
            });
        }
        $sizes = getimagesizefromstring($image);
        $headers = [
            'Content-Length' => strlen($image),
            'Content-Type' => $sizes["mime"]
        ];
        return \Response::make($image, 200, $headers);
    } else {
        return null;
    }
}

以这种方式工作时存在一个问题:我必须先从azure blob存储下载图像,然后系统才能检查是否存在调整了大小的缓存版本。

我正在使用的Azure软件包无法提供获取图像路径的功能,因此找不到解决我问题的另一种方法。

那么,有没有一种方法可以实现图像缓存而无需每次都下载文件?

1 个答案:

答案 0 :(得分:0)

我使用一条单独的路径在刀片中显示/缓存图像。 我将图像作为BLOB存储在product_id标识的MYSQL PRODUCT表中

刀片:

<img src="/dbimage/{{$product->id}}.png" >

路线:

Route::get('/dbimage/{id}',[ProductImageController::class, 'getImage']);

控制器:

class ProductImageController extends Controller
{

    public function getImage($prodcutImageID){
        $productID=explode(".",$prodcutImageID);
        $rendered_buffer= Product::all()->find($productID[0])->image;

        $response = Response::make($rendered_buffer);
        $response->header('Content-Type', 'image/png');
        $response->header('Cache-Control','max-age=2592000');
        return $response;
    }

}

这使浏览器缓存图像