设置为将php显示为图像(.png或.jpg)


Setting to display php as an image (.png or .jpg)

我有一个绘制图像的PHP源代码(一个绘制captcha的动态图像)。

它显示了一个动态生成的png文件。但在我将php移动到支持PHP5.x的免费web服务器后,它就没有显示了,而不是我公司的旧PHP 4.x服务器。

我之前更改了.htaccess文件,使"html"文件包含"php"代码。

我需要更改或添加.htaccess中的设置才能在新服务器中将"php"显示为图像文件吗?

它似乎不适用于一行:

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

在php文件中。

我在下面添加了php文件源代码供您参考:

<?php
session_start();
// Create the image
$im = imagecreatetruecolor(150, 50);
// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$gray = imagecolorallocate($im, 198, 198, 198);
//$black = imagecolorallocate($im, 0, 0, 0);
$textcol = imagecolorallocate($im, 38, 38, 38);
imagefilledrectangle($im, 0, 0, 399, 129, $gray);
// The text to draw
$text = empty($_SESSION['security_number']) ? 'error' : $_SESSION['security_number'];
$font = 'Georgia.ttf';
// Add some shadow to the text
//imagettftext($im, 20, 0, 11, 21, $grey, $font, $text);
// Add the text
imagettftext($im, 30, 0, 10, 35, $textcol, $font, $text);
imagepng($im);
imagedestroy($im);

?>

在PHP中生成PNG之前,必须添加header('Content-Type: image/png');,使其显示PNG(类似于JPG)。

此外,在设置标头之前,您必须检查imagepng()是否成功生成PNG。更重要的是,您必须验证是否安装了GD-Library。

另外,使用.htaccess制作HTML文件包含PHP代码是没有意义的;请改用PHP扩展。