PHP gd库用白色框代替图像显示黑屏

9njqaruj  于 2022-12-25  发布在  PHP
关注(0)|答案(2)|浏览(137)

我是PHP新手,目前正在使用XAMPP。我想使用gd库创建一个验证码图像,但我注意到我得到的只是一个中间有一个白色小框的黑屏。这是不管使用任何代码的输出。我尝试了不同网站的不同代码示例,但没有效果。我已经确认gd库已经启用。我已经卸载并重新安装了xampp。我也搜索了相关的问题,但没有一个建议的解决方案适合我。
这是我代码

session_start();

 // Set some important CAPTCHA constants
 define('CAPTCHA_NUMCHARS', 6);  // number of characters in pass-phrase
define('CAPTCHA_WIDTH', 100);   // width of image
define('CAPTCHA_HEIGHT', 25);   // height of image

// Generate the random pass-phrase
$pass_phrase = "";
for ($i = 0; $i < CAPTCHA_NUMCHARS; $i++) {
  $pass_phrase .= chr(rand(97, 122));
}

// Store the encrypted pass-phrase in a session variable
$_SESSION['pass_phrase'] = SHA1($pass_phrase);

// Create the image
$img = imagecreatetruecolor(CAPTCHA_WIDTH, CAPTCHA_HEIGHT); 
$bg_color = imagecolorallocate($img, 255, 255, 255);     // white
$text_color = imagecolorallocate($img, 0, 0, 0);         // black
$graphic_color = imagecolorallocate($img, 64, 64, 64);   // dark gray

// Fill the background
imagefilledrectangle($img, 0, 0, CAPTCHA_WIDTH, CAPTCHA_HEIGHT, $bg_color);

// Draw some random lines
for ($i = 0; $i < 5; $i++) {
  imageline($img, 0, rand() % CAPTCHA_HEIGHT, CAPTCHA_WIDTH, rand() % 
CAPTCHA_HEIGHT, 
  $graphic_color);
}

// Sprinkle in some random dots
for ($i = 0; $i < 50; $i++) {
  imagesetpixel($img, rand() % CAPTCHA_WIDTH, rand() % CAPTCHA_HEIGHT, 
$graphic_color);
}
// Draw the pass-phrase string
imagettftext($img, 18, 0, 5, CAPTCHA_HEIGHT - 5, $text_color, 'Courier New Bold.ttf', $pass_phrase);

// Output the image as a PNG using a header
header("Content-type: image/png");
imagepng($img);

// Clean up
imagedestroy($img);
  ?>

编辑:我已经能够将问题定位到标题(内容类型)行,但还没有找到解决方案。

3npbholx

3npbholx1#

经过几个小时的搜索不同的论坛。我已经开始更好地理解这个问题。问题不在于gd库,而在于标题(内容类型)行
当我决定创建一个图像文件而不是通过标头发送图像时。正确显示。
一旦我弄明白了这一点,找到解决方案变得更容易了,因为现在我正在正确的地方寻找解决方案。
问题是我的PHP脚本在输出PNG图像内容之前发出UTF-8字节顺序标记(EF BB BF)。
对我有效的解决方案是将ob_clean()放在标题行之前。
有关详细说明,请参阅下面的链接。https://stackoverflow.com/a/22565248/10349485
我使用和拼凑不同的解决方案,从不同的论坛,以更好地理解和达成这个解决方案,但上面的链接是我的最终目的地。
我不会删除这个问题,即使有其他类似的问题,因为我花了很多麻烦才得到和理解这个问题,也因为那里的答案对我不起作用。希望这能帮助未来的人避免我经历的麻烦。

bf1o4zei

bf1o4zei2#

从许多天我也面临这个问题,但这个解决方案为我工作使用__DIR__与您的字体文件路径一样

`$font_path = __DIR__ .'/font.ttf';`

相关问题