PHP - 创建&在飞行中渲染多个图像

时间:2016-09-01 22:52:51

标签: php html

请您看一下这段代码,让我知道为什么我无法动态地将生成的图像渲染到页面上?

<?php
 for ($i = 0; $i <= 3; $i++) {
   $im = imagecreatetruecolor(320, 80);
   $text_color = imagecolorallocate($im, 255, 255, 255);
   imagestring($im, 20, 20, 5,  "Test App", $text_color);

   $img = imagejpeg($im, 'Test.jpg');

   echo '<div class="map"><img src="'.$img.'" class="img-responsive" alt="Cinque Terre"></div>';

  imagedestroy($im);
  }
?>

我现在在输出中得到的是

enter image description here

虽然图片的src属性为1

enter image description here

4 个答案:

答案 0 :(得分:2)

捕获字节流,然后转换。您需要base64_encode原始字节。然后在图片标记中使用它:

基本理念:

for ($i = 0; $i <= 3; $i++) {
    ob_start(); // begin capture
    $im = imagecreatetruecolor(320, 80);
    $text_color = imagecolorallocate($im, 255, 255, 255);
    imagestring($im, 20, 20, 5,  "Test App " . ($i + 1), $text_color);

    $img = imagejpeg($im, null, 100);
    $raw = ob_get_clean(); // get

    echo '<div class="map"><img src="data:image/jpeg;base64,'.base64_encode($raw).'" class="img-responsive" alt="Cinque Terre"></div>';
}

答案 1 :(得分:0)

&lt; img&gt; tag期望您提供文件名。因此,您需要保存文件,然后引用保存的名称或您需要使用以下内容嵌入图像数据:

Embedding Base64 Images

答案 2 :(得分:0)

imagejpeg()根据其文档返回一个布尔值:PHP imagejpeg - 表示它是否成功创建了图像流。

在显示页面上,您可以执行以下操作:

<div class="map">
    <img src="image.php" class="img-responsive" alt="Cinque Terre">
</div>

创建一个名为image.php的文件,并将其设置为源:

<?php
  $im = imagecreatetruecolor(320, 80);
  $text_color = imagecolorallocate($im, 255, 255, 255);
  imagestring($im, 20, 20, 5,  "Test App", $text_color);

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

  $img = imagejpeg($im);

  imagedestroy($im);
?>

这实际上会将image.php视为图像文件。您必须在输出上正确设置标头,您的代码示例将不会这样做。浏览器需要知道如何处理数据流。

答案 3 :(得分:0)

也许最好有两个单独的PHP文件: 一个在运行中创建图像并将数据作为JPEG图像(比如image.php)返回,另一个呈现HTML代码的图像。 那么您的HTML将包含以下内容:

<img src="image.php?param1=value1&moreParams">

另一种选择是继续使用单个PHP文件,并将二进制JPEG图像转换为base64字符串。这是因为“src”属性需要“普通”URL或base64编码的图像数据。见这里:https://stackoverflow.com/a/21606233/4555850