首页 > 解决方案 > 图像处理未在缓存中更新

问题描述

在用户可以旋转上传图片的页面上,有一个旋转图片的按钮。这是使用干预图像完成的,但使用 PHP 已经实现了相同的结果(和问题)。

问题是图像旋转有效,但旋转后的图像未显示在浏览器中。这可能是缓存的原因,因为手动清空缓存时,旋转的图片确实在浏览器中显示。

public function rotate($picture_id) {

    // get picture location
    $path = Picture::where('id',$picture_id)->first()->location;

    // Rotate the picture
    $path_orig = storage_path('app/public/'.$path);
    $img_orig = Image::make($path_orig)
                ->rotate(-90)
                ->save($path_orig);

    // Rotate thumbnails etc
    ...

    return Redirect::back();
}

解决方案 使用随机字符串更新文件名。

public function rotate($picture_id) {

    // get picture location
    $path = Picture::where('id',$picture_id)->first()->location;

    // Path to picture
    $path_orig = storage_path('app/public/'.$path);
    $path_s = public_path($path);

    // New path
    do {
        $newKey = str_random(40);
        $ext = File::extension($path_orig);
        $dir = dirname($path_orig);
        $path_L_new = $dir.'/'.$newKey.'.'.$ext;
        $path_S_new = public_path('folder/'.$newKey.'.'.$ext);
    }
    while ( count(Picture::where('location',$path_L_new)->get()) > 0 );

    // Rotate images
    $img_L_new = Image::make($path_orig)
                ->rotate(-90)
                ->save($path_L_new);

    $img_S_new = Image::make($path_s)
                ->rotate(-90)
                ->save($path_S_new);

    // Delete old files
    Storage::delete($path);
    File::delete(public_path($path));

    // Update location
    $pic = Picture::where('id',$picture_id)->first()->update(array('location' => 'folder/'.$newKey.'.'.$ext));

    // Show new picture
    return Redirect::back();

}

标签: phplaravelcachingintervention

解决方案


您必须在图像 src 处附加一个随机或唯一的字符串:

<img src="/path/to/file.jpg{{ time() }}">

但请注意,当图像未更新时,不要将新的随机字符串附加到图像 src 的末尾。如果这样做,图像将不会被缓存。

正确方法:当图像更新时,最好为该图像存储一个随机字符串并将其存储在数据库中。并且在显示图像时,向其附加对等随机字符串。不要在每次调用时生成新的随机字符串。


推荐阅读