html可以在php中与动态生成的图像一起使用吗?


Does html can be use with dynamic generated images in php?

我正在使用这个代码创建一个图像

<?php
 // Set the content-type
 header('Content-Type: image/png');
 // Create the image
 $im = imagecreatetruecolor(400, 30);
 // Create some colors
 $white = imagecolorallocate($im, 255, 255, 255);
 $grey = imagecolorallocate($im, 128, 128, 128);
 $black = imagecolorallocate($im, 0, 0, 0);
 imagefilledrectangle($im, 0, 0, 399, 29, $white);
 // The text to draw
 $text = 'Testing...';
 // Replace path by your own font path
 $font = 'arial.ttf';
 // Add some shadow to the text
 imagettftext($im, 20, 0, 11, 21, $grey, $font, $text);
  // Add the text
  imagettftext($im, 20, 0, 10, 20, $black, $font, $text);
  // Using imagepng() results in clearer text compared with imagejpeg()
  (A)print ('<div class="test">');
  imagepng($im);
  print ('</div>');
  (B)imagedestroy($im);
  ?>

如果我注释行号'A'和'B',代码工作fine,它在浏览器上生成图像,并在其上编写测试。但我希望图像是在div.所以我取消注释行(a)和(B),但它没有给出正确的输出。生成的html也很奇怪生成的html是

<img src="http://localhost/php/test92.php" alt="The image “http://localhost/php/test92.php” cannot be displayed, because it contains errors.">

基本上,要在HTML中创建动态图像,您将需要2个PHP文件:

  1. 一个用于图像本身
  2. 另一个用于PHP显示的参数

让我们看看怎么做:

  1. 您创建image.php接受参数,如:图像ID或文件名。为了安全起见,你必须过滤它得到的任何参数。

    你为什么要这么做?因为要生成图像,不能将其与其他HTML输出混合。更不用说单个spacereturn,因为这会使图像破碎。

  2. 你做HTML的事情在另一个PHP,说test92.php。到这里的HTML逻辑,如:

    1. 获取图像数据
    2. 循环数据
    3. display image => <img src="image.php?imageID=12" alt="" />

如果你想在图像周围设置div你必须在html中设置,而不能在图像生成代码中设置

<div>
<img src="http://localhost/php/test92.php">
</div>

如果你得到关于图像的错误,试着浏览图像url http://localhost/php/test92.php,看看它是什么样子的

显示的是您所期望的图像吗?