优化图像输出性能
我有一个 php 文件,用于检查图像是否可用。如果是,则图像将返回给用户,如果不是,则将创建图像然后返回给用户。
if(file_exists($filepath)) {
$fp = fopen($filepath, 'rb'); # stream the image directly from the cachefile
fpassthru($fp);
exit;
}
我想为了优化这个我可以跳过“file_exists”调用并尝试“fopen”它,如果返回“false”我创建图像,否则我直接返回它(正确吗?)。
我想知道的是,这是在 PHP 中加载图像最快的方法吗?在此之前,我使用 imagepng($image)
但读到 fpassthru 速度更快: http://www.php.net/manual/en/function.imagepng .php#103787
I have a php file which checks if an image is available. If it is, the image will be returned to the user, if not it will be created and then returned to the user.
if(file_exists($filepath)) {
$fp = fopen($filepath, 'rb'); # stream the image directly from the cachefile
fpassthru($fp);
exit;
}
I guess to optimize this I can skip the "file_exists" call and just try to "fopen" it, if "false" is returned I create the image, otherwise I directly return it (is that correct?).
What I want to know is, is this the fastest way to load an image in PHP? Before that I used imagepng($image)
but read that fpassthru is way faster:
http://www.php.net/manual/en/function.imagepng.php#103787
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最快的方法就是一开始就不要通过 PHP 处理图像。使用反向代理服务器,它为现有文件提供服务,并且对于每个不存在的文件,它调用 PHP 脚本。
接下来,删除对 file_exists() 的调用是微优化;但是,如果文件不存在,PHP 将触发警告,将其写入日志,根据设置输出...就 CPU 而言,这比 file_exists 调用更昂贵。
The fastest way is not to process the image via PHP in the first place. Use reverse proxy server, which serve existing files, and for each not existing file it call's the PHP script.
Next, removing call to file_exists() is microoptimization; however if the file do not exists PHP will trigger warning, write it to the log, output it depending on settings... which in terms of CPU is more expensive than the file_exists call.