从 php 页面内的字符串动态呈现 jpg/png

Dynamically Render jpg/png from string inside php page

我需要在呈现页面时从字符串(用户的电话号码)呈现图像 (png)。可以在 php 页面内渲染图像吗?或者我必须专门创建一个页面来呈现图像并包含它?

如果我在 php 页面中使用此代码,则无法正常工作

    <?php
// Create a 100*30 image
$im = imagecreate(100, 30);

// White background and blue text
$bg = imagecolorallocate($im, 255, 255, 255);
$textcolor = imagecolorallocate($im, 0, 0, 255);

// Write the string at the top left
imagestring($im, 5, 0, 0, 'Hello world!', $textcolor);

// Output the image
header('Content-type: image/png');

imagepng($im);
imagedestroy($im);
?>

http://php.net/manual/en/function.imagestring.php

我必须声明 "header('Content-type: image/png')" 或者有其他方法来渲染 png?因为如果我声明它,则不会呈现页面的其他部分。

我正在使用 Zend Framework 2

按照他的建议,我尝试使用 base64 方式并且工作正常

    <?php 
 ob_start (); 
 $im = @imagecreate(110, 20)
    or die("Cannot Initialize new GD image stream");

$background_color = imagecolorallocate($im, 0, 0, 0);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  "A Simple Text String", $text_color);
imagepng($im);

$image_data = ob_get_contents (); 

ob_end_clean (); 

$image_data_base64 = base64_encode ($image_data);

?>
<img src="data:image/png;base64,<?php echo $image_data_base64; ?>" alt="img"/ >

disclaymer 这是一个测试,不要在您的站点中应对和使用此代码,它是不安全的。

与所有网页一样 - 图片不是 HTML 的一部分 - 它们是单独的文件。所以是的,您必须创建一个单独的文件并为您的图像设置适当的 headers。然后只需将文件的 url 包含在图像的来源中。

请记住,如果您的 url 类似于 "file.php?number=123456",那么机器人很容易知道 phone 数字,这只会破坏图像的目的(如果我正确地假设了目的)。

或者,您可以生成图像,将其转换为 base64 并将其作为 data-uri 嵌入到实际的 HTML 源中。我不建议这样做,但如果您有兴趣,只需 google "html data-uri" - 您会找到很多示例。

我同意马吕斯的观点。最好调用另一个文件来生成图像。

<img src="phoneimg.php?n=123-456-7890.png" />
// or base64_encode() the number
<img src="phoneimg.php?n=MTIzLTQ1Ni03ODkw.png" />

使用 url 查询字符串发送号码、分机号、大小等。请记住在继续之前过滤和清理传入的查询。