我想使用PHP imagettftext生成验证码图像。以下是我的代码。它给出一个空图像。我想解决这个问题。
我已经测试了代码,但是尽管我的随机文本被传递给验证码图像生成功能,但无法找到为什么未显示图像的原因。
<?php
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
function generateCaptchaImage($text = 'good'){
echo $text;
echo 'OK';
// Set the content-type
header('Content-Type: image/png');
$width = 200;
$height = 30;
$font = 'ThisisKeSha.ttf';
// Create the image
$im = imagecreatetruecolor($width, $height);
//ADD NOISE - DRAW background squares
$square_count = 6;
for ($i = 0; $i < 10; $i++) {
$cx = (int)rand(0, $width/2);
$cy = (int)rand(0, $height);
$h = $cy + (int)rand(0, $height/5);
$w = $cx + (int)rand($width/3, $width);
imagefilledrectangle($im, $cx, $cy, $w, $h, $white);
}
//ADD NOISE - DRAW ELLIPSES
$ellipse_count = 5;
for ($i = 0; $i < $ellipse_count; $i++) {
$cx = (int)rand(-1*($width/2), $width + ($width/2));
$cy = (int)rand(-1*($height/2), $height + ($height/2));
$h = (int)rand($height/2, 2*$height);
$w = (int)rand($width/2, 2*$width);
imageellipse($im, $cx, $cy, $w, $h, $grey);
}
// Add the text
imagettftext($im, 20, 0, 10, 20, $black, $font, $text);
imagepng($im);
}
$randomString = generateRandomString();
generateCaptchaImage($randomString);
?>
最佳答案
从评论中解决
未定义$white
和$black
。
删除echo $text;
和echo 'OK';
。
服务器上的ThisisKeSha.ttf
是否与此目录相同?
未定义$white
和$black
。