1

我使用以下代码为我的表单创建验证码。验证码创建良好。现在我想更改字体大小和字体字符空间。我不知道如何更改以下代码。

      <?php
             session_start();
             $code= substr(str_shuffle("abcdefghijklmnopqrstuvwxyz"), 0, 6);
             $_SESSION["code"]=$code;
             $im = imagecreatetruecolor(150, 35);
             $bg = imagecolorallocate($im, 255, 255, 255);
             $fg = imagecolorallocate($im, 0, 0, 0);
             imagefill($im, 5, 5, $bg);
             imagestring($im, 5, 8, 8,  $code, $fg);
             header("Cache-Control: no-cache, must-revalidate");
             header('Content-type: image/png');
             imagepng($im);
             imagedestroy($im);
        ?>
4

2 回答 2

2

您可以使用imagestring函数更改字体

于 2013-10-28T05:39:36.303 回答
2

您可以使用下面的代码使用 PHP 的 gd 库来实现一个简单的验证码。作为初学者,这里有一个用于快速测试的示例代码,它还涵盖了字体大小:

<?php
session_start();
header('Content-type: image/jpeg');

$text = rand(1000, 9999);
$font_size = 30;

$image_width = 200;
$image_height = 40;

$image = imagecreate($image_width, $image_height);
imagecolorallocate($image, 255, 255, 255);
$text_color = imagecolorallocate($image, 0, 0, 0);

for ($x=1; $x<=40; $x++) {
     $x1 = rand(1, 100);
     $y1 = rand(1, 100);
     $x2 = rand(1, 100);
     $y2 = rand(1, 100);

 imageline($image, $x1, $y1, $x2, $y2, $text_color);
}

imagettftext($image, $font_size, 0, 15, 30, $text_color, 'FREESCPT.ttf', $text);
imagejpeg($image);

?>

在 imagettftext 函数中:

imagettftext($image, $font_size, $angle, $x, $y, $text_color, '$font-family', $text);

  $image is the $imagecreate function
  $font_size is the size of font you want.
  $angle is the angle of the fonts tilted
  $x and $y are coordinates.
  $text_color is the imagecolorallocate function
  $font-family is the family of font you want to use
  $text is the text or random text to be displayed

这是关于如何在 php 中构建验证码的好教程 ->链接

于 2013-10-28T06:09:54.447 回答