【问题标题】:PHP gd library displsys black screen with white box instead of imagePHP gd 库显示黑屏和白框而不是图像
【发布时间】:2020-04-14 05:00:08
【问题描述】:

我对 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);
  ?>

编辑: 我已经能够将问题定位到标题(内容类型)行。 还没有想出解决办法。

【问题讨论】:

    标签: php xampp gd


    【解决方案1】:

    经过几个小时的搜索不同论坛。我已经更好地理解了这个问题。问题不在于 gd 库,而在于 header(Content-type) 行

    当我决定创建图像文件而不是通过标题发送图像时。正确显示。

    一旦我明白了这一点,找到解决方案就变得更容易了,因为我现在正在正确的地方寻找解决方案。

    问题是我的 PHP 脚本在输出 PNG 图像内容之前发出了 UTF-8 字节顺序标记 (EF BB BF)。

    对我有用的解决方案是将 ob_clean() 放在标题行之前。

    有关详细说明,请参阅下面的链接。 https://stackoverflow.com/a/22565248/10349485

    我使用并拼凑了来自不同论坛的不同解决方案,以便更好地理解并得出这个解决方案,但上面的链接是我的最终目的地。

    即使还有其他类似的问题,我也不会删除该问题,因为我费了很大力气才能理解和理解这个问题,也因为那里的答案对我不起作用。希望这可以帮助将来的人避免我遇到的麻烦。

    【讨论】:

    • 我也有同样的问题。我看到一个小白框而不是图像。我在标题之前运行了 ob_clean(),但是它没有用。我注意到如果我不在标题之前运行 ob_clean(),我有两个空格。如果我运行 ob_clean(),我只有 1 个空格。您认为这些空白是否与问题有关?
    猜你喜欢
    • 2019-04-12
    • 2011-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多