PHP gd 从生成的图像制作缩略图

PHP gd make thumbnail from generated image

我有一个 php 脚本 cakeChart.php 可以生成简单的蛋糕。

$image = imagecreatetruecolor(100, 100);

$white    = imagecolorallocate($image, 0xFF, 0xFF, 0xFF);
$gray     = imagecolorallocate($image, 0xC0, 0xC0, 0xC0);
$navy     = imagecolorallocate($image, 0x00, 0x00, 0x80);
$red      = imagecolorallocate($image, 0xFF, 0x00, 0x00);

imagefilledarc($image, 50, 50, 100, 50, 0, 45, $navy, IMG_ARC_PIE);
imagefilledarc($image, 50, 50, 100, 50, 45, 75 , $gray, IMG_ARC_PIE);
imagefilledarc($image, 50, 50, 100, 50, 75, 360 , $red, IMG_ARC_PIE);


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

在文件 createThumb.php 中,我想从 cakeChart.php 加载生成的图像。 像(我知道这很糟糕):

$pngImage = imagecreatefrompng("pieChart.php");

我想制作这张图片的缩略图。目前关于这个 php 文件的唯一参考是这个

<a href="pieChart.php" target="blank">PHP pie chart</a><br>

但我想用 tumb 替换此文本,whitch 将在 createThumb.php 中生成。是否可以使用 cakeChart.php 制作图像,然后使用 createThumb.php 将其转换为缩略图?

您需要另一个调用 cakeChart.php 并调整其大小的脚本,如下所示:

<?php
$src = imagecreatefrompng('http://example.com/cakeChart.php');

$width = imagesx($src);
$height = imagesy($src);
// resize to 50% of original:
$new_width = $width * .5;
$new_height = $height * .5;

$dest = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($dest, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

header('Content-type: image/png');
imagepng($dest);
imagedestroy($dest);
imagedestroy($src);

然后您的 HTML 将引用该文件作为图像源:

<a href="pieChart.php" target="blank">
    <img src="http://example.com/cakeChartThumb.php" alt="PHP pie chart">
</a>

虽然这会奏效,但无法有效利用服务器资源。即使是少量的页面浏览量也可能导致服务器 CPU 使用率激增并影响性能。您真的应该一次创建这两个文件并将它们保存到磁盘,在您的 HTML 中引用它们,就像您引用任何其他图像文件一样。