如何将PHP绘制的图像包装到HTM img标签中

时间:2015-10-05 19:02:35

标签: php php-5.6

是否可以在HTML标记中扭曲PHP图像并将其发送到客户端

echo '<img src='+ $ima+' alt=' ' />';

类似

<?php
$a = "A";
$b = "B";
$c = "C";
$n = "8";

$ima = imagecreate(100, 30);
$bg = imagecolorallocate($ima, 255, 255, 255);
$textcolor = imagecolorallocate($ima, 0, 0, 255);
imagestring($ima, 5, 0, 0, '$a, $textcolor);
header('Content-type: image/png');
imagepng($ima);
imagedestroy($ima);

$imb = imagecreate(100, 30);
$bg = imagecolorallocate($imb, 255, 255, 255);
$textcolor = imagecolorallocate($imb, 0, 0, 255);
imagestring($imb, 5, 0, 0, '$a, $textcolor);
header('Content-type: image/png');
imagepng($imb);
imagedestroy($imb);

$imc = imagecreate(100, 30);
$bg = imagecolorallocate($imc, 255, 255, 255);
$textcolor = imagecolorallocate($ima, 0, 0, 255);
imagestring($imc, 5, 0, 0, '$a, $textcolor);
header('Content-type: image/png');
imagepng($imc);
imagedestroy($imc);

$imn = imagecreate(100, 30);
$bg = imagecolorallocate($imn, 255, 255, 255);
$textcolor = imagecolorallocate($ima, 0, 0, 255);
imagestring($imn, 5, 0, 0, '$a, $textcolor);
header('Content-type: image/png');
imagepng($imn);
imagedestroy($imn);

echo '<img src="script.php?id=1" />';
echo '<img src="script.php?id=2" />';
echo '<img src="script.php?id=3" />';
echo '<img src="script.php?id=4" />';
?>

更新

"t 1 : n1   t t 2 : n2   t t t 3 : n3"

2 个答案:

答案 0 :(得分:1)

是的。您需要做的是在图像标记中引用您的PHP脚本。

<img src="yourPhpScript.php" />

确保在PHP脚本中输出正确的Content-Type标题。

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

或者,您可以base64-encode the image data,但不建议这样做,因为它会导致下载量增加33%。

此外,您在最后一行的第三行中有一个迷路引号'

答案 1 :(得分:0)

您可以使用输出缓冲区捕获。

 $a = "A";
 $ima = imagecreate(100, 30);
 $bg = imagecolorallocate($ima, 255, 255, 255);
 $textcolor = imagecolorallocate($ima, 0, 0, 255);
 imagestring($ima, 5, 0, 0, $a, $textcolor);
 ob_start();
 imagepng($ima);
 $obContents = ob_get_contents();
 ob_end_clean();
 imagedestroy($ima);
 echo('<img src="data:image/png;base64,' . base64_encode($obContents) . '" />');