PHP:动态生成文本中的png

时间:2012-08-11 14:12:01

标签: php png gd

我写了这个函数来从文本创建png文件:

function pngfromtext($text){
    $fontsize = 5;
    $width = imagefontwidth($fontsize)* strlen($text);
    $height = imagefontheight($fontsize);

    $img = imagecreate($width, $height);

    // Transparent background
    $black = imagecolorallocate($img, 0, 0, 0);
    imagecolortransparent($img, $black);

    // Red text
    $red = imagecolorallocate($img, 255, 255, 255);
    imagestring($img, $fontsize, 0, 0, $text, $red);

    header('Content-type: image/png');
    imagepng($img);
    imagedestroy($img);
}

我将代码放到functions.php文件中,当在另一个页面中使用此函数时,我收到此错误:

 Warning: Cannot modify header information - headers already sent by (output started at ..\functions.php on line 58
�PNG  IHDRZ^%JPLTE����ٟ�tRNS@��f�IDAT�c` Hȱ�7�H��'��`c��s�����i��$���Hl`8��Ɛ�� ��#�c��p�� q�3f�òm�� �g�ـ�6fF ���h�bc�sXd4c�A4����?|�¦����r+���!IEND�B`�

有什么问题?

3 个答案:

答案 0 :(得分:2)

将标题设置在您知道输出将成为图像的位置。这意味着设置此声明

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

在php脚本的开头。

此处之前还有可能已经执行了header-command。

答案 1 :(得分:1)

header('Content-type: image/png');ob_clean();之前

清理响应对象,以便您可以再次添加标题

答案 2 :(得分:1)

您无法在页面上使用多个标题。