图片缓存无法显示新编辑的图片

3
我正在构建一个 PHP 脚本,用于在背景图像上编写文本。我使用了 GD 函数,例如 imagecopy()、imagejpeg() 和 imagedestroy() 来合并和保存文本图像和背景图像。一切都运作得很完美。在提交表单后,新的图像将保存在与背景图像相同的文件名中,因此在重新加载页面时,编辑后的图像不会显示在浏览器中。需要按下 ctrl + F5(在 Windows 上)刷新页面以加载编辑后的图像。有谁能帮助我清除缓存?

"有人能帮我清除缓存吗?" - 你指的是什么? - Pedro Lobito
2个回答

4
每次编辑背景图像时,在背景路径末尾添加?v=something即可,它将强制刷新。

我无法从 PHP 中加载图像。在 HTML 页面上加载背景图像(使用 img 标签),让用户在背景图像上添加文本(图像文本),并使用 PHP 合并和保存图像。保存后重新加载页面,它显示旧的未编辑的背景图像,直到我按下 Ctrl+F5。 - devdarsh
1
啊,这个。每次编辑你的背景图像时,只需在 bgpath 后面添加 ?v=something,它将强制刷新。 - genesis

1

为了正确处理图像缓存,您可以在Apache配置或htaccess中编写规则...或者您可以创建一个简单的"图像提供程序",类似于...

(Note: The translated text is in Simplified Chinese.)
public function img($imgfile = '')
{
    $imgfile = $_GET['q'];
    $age = 60*60*24*31;
    $file = $_SERVER['DOCUMENT_ROOT'].'/'.$imgfile;

    if ( ! file_exists($file))
    {
       header('HTTP/1.0 404 Not Found');
    }
    else
    {
       $last_modified = filemtime($file);

        // Check for cached version
        if(isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) OR isset($_SERVER['HTTP_IF_NONE_MATCH'])) 
        {
           if ($_SERVER['HTTP_IF_MODIFIED_SINCE'] == gmdate('D, d M Y H:i:s \G\M\T', $last_modified)) 
           {
               header('HTTP/1.0 304 Not Modified');
               exit;
           }
        }   
        if(strpos($imgfile,'.png') !== FALSE)
        {
            Header('Content-Type: image/png');
        }
        elseif(strpos($imgfile,'.jpg') !== FALSE || strpos($img_file,'.jpeg') !== FALSE)
        {
            Header('Content-Type: image/jpg');
        }
        elseif(strpos($img_file,'.gif') !== FALSE)
        {
            Header('Content-Type: image/gif')
        }

        Header('Last-Modified : '.gmdate('D, d M Y H:i:s \G\M\T', $last_modified));
        Header('Cache-Control : max-age='.$age.', must-revalidate');
        Header('Expires : '.gmdate('D, d M Y H:i:s \G\M\T', $last_modified + $age));
        echo file_get_contents($file);
}

然后你可以在你的图像标签中使用它,例如<img src="provider.php?q=foo.jpg" alt="Foo" />


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接