图像PNG 非常慢


imagepng Very Slow

我有一个.php文件,它应该加载图像以显示在img标签
(即<img src="the_file.php?which=0"/>)。 它看起来像这样:

<?php
    ob_clean();
    header("Content-type: image/png");
    include_once("util.php");
    //Do a simple calculation to get $name from (int)$_GET["which"];
    $im = imagecreatefrompng("protected_directory/".$name.".png");
    imagepng($im,NULL,0,NULL);
    imagedestroy($im);
    ob_end_flush();
?>

工作正常,但图像加载速度比直接
加载它慢得多(即 <img src="protected_directory/the_name.png"/> ,其中"the_name"的计算方式与 PHP 文件中的计算方式相同,但我不能只是这样做,因为protected_directory不是世界可读的)。

我的问题是,为什么突然变慢了这么多? 这不是一个大图像,但也不是很小。

如果您只是显示现有文件,请使用 readfile() 将其输出到浏览器。无需为此创建可编辑的 GD 对象的所有开销。

已知

imagepng很慢,如果您需要使用 PHP 脚本输出图像,请使用如下代码:

$filename = md5(time() . mk_rand());
imagepng($im, $filename);
echo file_get_contents($filename);

作为另一个答案,我想出您可以使用第三个参数来压缩图像(PNG 使用 zlib)。 将其设置为 9 与其他解决方案一样有效。