简体   繁体   English

如何强制浏览器缓存按需生成的图像?

[英]How to force browser to cache on-demand generated images?

An URL such as http://mydomain.com/text/SGVsbG8gd29ybGQh/params/Y29sb3I9I2Y5NzMwNixmb250LWZhbWlseT1Db21pYyBTYW5zLGZvbnQtc2l6ZT0yMnB4LGZvbnQtd2VpZ2h0PWJvbGQsZm9udC1zdHlsZT1ub3JtYWwsdGV4dC1kZWNvcmF0aW9uPW5vbmUsdGV4dC1hbGlnbj1sZWZ0/96 calls on a PHP script that generates an image based on the encoded information contained within the URL. 诸如URL http://mydomain.com/text/SGVsbG8gd29ybGQh/params/Y29sb3I9I2Y5NzMwNixmb250LWZhbWlseT1Db21pYyBTYW5zLGZvbnQtc2l6ZT0yMnB4LGZvbnQtd2VpZ2h0PWJvbGQsZm9udC1zdHlsZT1ub3JtYWwsdGV4dC1kZWNvcmF0aW9uPW5vbmUsdGV4dC1hbGlnbj1sZWZ0/96呼吁,其基于包含在URL中的编码信息的图像的PHP脚本。 The information encode is the actual text, plus some formatting options (eg color, font-weight etc.). 信息编码为实际文本,再加上一些格式设置选项(例如颜色,字体粗细等)。

The first time this URL is called, the image is generated, saved to disk and then returned as the response. 第一次调用此URL时,将生成图像,将其保存到磁盘,然后作为响应返回。 Starting with the second call to the same URL, the image is loaded from disk and output to the client instead of being generated all over again. 从对同一URL的第二次调用开始,图像从磁盘加载并输出到客户端,而不是重新生成。

How can I force the browser to treat such a URL as any other path to a stored image file and cache it, so that the next time the URL is called, the browser will load the image from its cache? 如何强制浏览器将此类URL视为已存储图像文件的任何其他路径并将其缓存,以便下次调用该URL时,浏览器将从其缓存中加载图像?

Btw, the code I have in the controller (CodeIgniter-based) is as follows: 顺便说一句,我在控制器中的代码(基于CodeIgniter)如下:

public function addText($text, $params, $resolution=96) {
        $this->load->model("textimage_model");
        $image = $this->textimage_model->getImage($text, $params, $resolution);

        // Prepare the response headers and output the image to the client
        header("Content-type: image/png");
        header("Content-disposition: inline; filename=mytext.png");

        if (is_string($image)) {
            readfile($image);
        } elseif (is_resource($image)) {
            imagepng($image);
            imagedestroy($image);
        } else {
            //
        }

    }

Send caching headers. 发送缓存头。

$seconds_to_cache = 60 * 60 * 24; // 1 day
header("Pragma: cache");
header("Cache-Control: max-age=" . $seconds_to_cache);

Since your caching mechanism seems to be a fingerprint you can have the browser cache it forever. 由于您的缓存机制似乎是一种指纹,因此您可以让浏览器将其永久缓存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM