简体   繁体   中英

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

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.">

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="" />

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM