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

时光毁灭记忆、已成空白 提交于 2019-12-20 02:38:04

问题


I am using this code to create an image

<?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);
  ?>

The code work fines if i comment the line number 'A' and 'B' and it generates the image on the browser with testing written on it. But i want the image to be in a div. so i uncomment the line (A) and (B) but it is not giving right output. The generated html is also strange generated html is

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

回答1:


Basically, to create dynamic image in HTML, you will need 2 PHP files:

  1. one for the image itself
  2. another one for PHP to display it.

Let's take a look how to do it:

  1. You create image.php that accept parameter, like: image ID or file name. For security reason, you HAVE to filter whatever parameter it get.

    Why you have to do this? because, to generate image, you can't mix it with another HTML output. Let alone a single space or return as this will render the image broken.

  2. You do the HTML thing on another PHP, say test92.php. To the HTML logic here, like:

    1. get image data
    2. loop the data
    3. display image => <img src="image.php?imageID=12" alt="" />



回答2:


If you want a div around your image you have to do that in the html, you can't do that in the image generation code

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

If you are getting errors regarding the image, try browsing the image url http://localhost/php/test92.php and see what it looks like.

Does it show an image like you are expecting?



来源:https://stackoverflow.com/questions/7886064/does-html-can-be-use-with-dynamic-generated-images-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!