如何在 HTML 页面中直接输出动态创建的图像?

How can I output a dynamically created image directly within a HTML page?

我有一个 HTML 页面。在此页面上,我想显示动态创建的 PNG 图像 ,而不先将其保存到文件中

当我只是尝试在页面中创建图像时,我当然会收到一条错误消息,指出 headers 已发送。


示例代码:

<!doctype html>
<html>
<head>
    <title>A Test Page</title>
</head>
<body>
    <h1>An Image</h1>
<?php

$im = imagecreatetruecolor(100, 100);
$white = ImageColorAllocate ($im, 255, 255, 255);
$black = ImageColorAllocate ($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 50, 50, $white);
imagefilledrectangle($im, 0, 50, 50, 100, $black);
imagefilledrectangle($im, 50, 0, 100, 50, $black);
imagefilledrectangle($im, 50, 50, 100, 100, $white);
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);

?>
</body>
</html>

你可以做的是将图像缓冲在一个变量中,然后将 img 编码为 base64:

ob_start(); 
imagepng($im); 
$img_content = ob_get_contents(); 
ob_end_clean(); 

$dataUri = "data:image/png;base64," . base64_encode($img_content);
echo '<img src="' . $dataUri . '">';