因此,不要对学习者过于严格,Marc B 建议的解决方案是更仔细地研究imagejpeg() 函数:
bool imagejpeg ( resource $image [, string $filename [, int $quality ]] )
所以有第二个可选参数$filename,当给定它时,它将告诉GD将图像存储在该文件中。
但是它还说,如果你传递一个文件名,图像不会自动输出到浏览器,如果你不传递第二个参数就会发生这种情况。
因此,您必须完成三个步骤:
创建唯一的文件名
将图像保存到文件
在浏览器中显示图片
现在最简单的解决方案是:
/* --- create unique filename --- */
// get name passed or set default, this will be prepended to
// the unique filename to make it more readable
$prepend_filename = (isset($_GET['name']) ? rawurlencode(trim($_GET['name'])) : 'ing';
// set to the path where you want your images stored
$dirname = "/your/base/path/wherever/";
// use a while loop to make sure or new filename does not exist
while (true) {
// now build unique filename
$filename = uniqid($prepend_filename, true) . '.jpg';
// if filename is unique (file does not exist) then exit loop
if (!file_exists($dirname . $filename)) break;
}
/* --- save image to file --- */
imagejpeg( $jpg_image, $dirname . $filename );
/* --- output image to browser --- */
readfile($dirname . $filename);
所以这基本上可以工作。该解决方案唯一不太好的地方是,首先您访问磁盘以写入图像,然后您必须重新访问文件以将其输出到浏览器。您可以使用另一种技术来减少文件访问:
/* --- output image to browser ---*/
// use output buffering to capture outputted image stream
ob_start();
// output the image to output buffer
imagejpeg($jpg_image);
// stop capture, flush output to browser and save as string
$img_data = ob_get_flush();
/* --- save image to file --- */
$fp = fopen($dirname . $filename, 'w');
fwrite($fp, $img_data);
fclose($fp);
所以这样做的好处是,您不必访问磁盘两次。
如果您不想将图像作为原始图像格式返回,但实际上想在您的 html 页面中立即显示,有两种方法。
方法一(去掉上面重复部分的cmets)这里我们创建图像,保存文件并使用我们创建的文件名生成html输出。
<?php
/* --- create unique filename --- */
$prepend_filename = (isset($_GET['name']) ? rawurlencode(trim($_GET['name'])) : 'ing';
$dirname = "/your/base/path/wherever/";
while (true) {
$filename = uniqid($prepend_filename, true) . '.jpg';
if (!file_exists($dirname . $filename)) break;
}
/* --- save image to file --- */
imagejpeg( $jpg_image, $dirname . $filename );
// now the difference starts
?><html>
<head>
<title>Your title here</title>
<!-- the rest of your head here -->
</head>
<body>
<img src="http://yourserver.com/your/base/path/wherever/<?php
echo $filename;
?>" width="100%" />
</body>
</html>
方法二 开始同上,区别在保存图片时开始,我们再次使用输出缓冲的方法,但这次我们将输出作为base64编码的字符串传递给img标签。讨厌,讨厌:)
/* Generating the filename is the same as above (not copied here).
Output buffering same as prior sample, with one difference:
Now we use ob_get_clean() instead of ob_get_flush() because
we do not want to output image.
*/
ob_start();
imagejpeg($jpg_image);
$img_data = ob_get_clean(); // NOTE: ob_get_clean() not ob_get_flush()
/* --- save image to file --- */
$fp = fopen($dirname . $filename, 'w');
fwrite($fp, $img_data);
fclose($fp);
?><html>
<head>
<title>Your title here</title>
<!-- the rest of your head here -->
</head>
<body>
<img src="data:image/jpeg;base64,<?php
echo base64_encode( $img_data );
?>" width="100%" />
</body>
</html>
所以这里我们使用缓冲的$img_data 将文件写入磁盘并直接在html页面中输出,而无需浏览器从服务器调用文件(但显然具有更大的html源)