PHP GD-输出和保存之间的性能/时间差


PHP GD - performance/time difference between output and save

使用php和gd-在以下两者之间执行对性能或时间有什么好处:

输出图像

header('Content-Type: image/png');
imagepng($image);

或者将图像保存到服务器(本地服务器或Amazons3)

imagepng($image, 'new_image.png');

好吧,生成图像数据所需的时间不会有差异,因为在这两种情况下都是相同的。

然而,当您将图像保存到本地磁盘时,操作可能会比数据必须发送到世界某个地方的客户端浏览器时终止得快得多。

然而,PHP的目的是在浏览器中显示一些东西,所以我想你无论如何都会显示存储的文件,从而否定了你从存储图像中获得的任何速度优势。

因此,如果您想在这两种情况下都显示图像,我想最好直接从PHP脚本输出图像。

另一方面,如果您多次使用图像,那么您应该保存它,并使用保存的版本,因为在PHP中生成图像本身需要时间。

如果你想生成一次,并使用多次,你可以使用这段PHP代码:

<?php
// this is where it is stored
$filename = 'my_image.png';
// test if file exists
if (!file_exists($filename))
{
  // if does not exist, make it
  <... your code for making the image ...>
  // store to disk
  imagepng($image,$filename);
  // image is not needed anymore
  imagedestroy($image);
}  
// header
header('Content-Type: image/png');
// get file from the disk
readfile($filename);
?>

如果您已经更改了映像并想重新生成它,只需将其从磁盘中删除即可。这是一个非常基本的示例,您可以根据需要在其上进行构建。