1.gd库

php gd库的功能比较强大,主要用来做图片验证码生成,绘制图片,处理图片等等。下面是简单的gd库绘制图片验证码

代码示例

$size_x = 100;
$size_y = 100;

if(!isset($_GET['code'])) {
    $code = 'unknown';
}
$space_per_char = $size_x /(strlen($code)+1);

$img = imagecreatetruecolor($size_x,$size_y);
$background = imagecolorallocate($img,255,255,255);//白色
$border = imagecolorallocate($img,128,128,128);
$colors[] = imagecolorallocate($img,128,64,192);
$colors[] = imagecolorallocate($img,192,64,128);
$colors[] = imagecolorallocate($img,108,192,64);

imagefilledrectangle($img, 1, 1,$size_x - 2, $size_y - 2, $background);
imagerectangle($img, 1, 1,$size_x - 2, $size_y - 2, $border);

for($i = 0;$i < strlen($code);$i++) {
    $color = $colors[$i % count($colors)];
    imagettftext(
        $img,
        28 +rand(0,8),
        -20 +rand(0,40),
        ($i + 0.3) * $space_per_char,
        50 + rand(0,10),
        $color,
        'font/arial.ttf',
        $code{$i}
    );
    imageantialias($img,true);
}
header('Content-type:image/png');
imagepng($img);

结果
图片描述
即,known就绘制成图片。可以验证了

2.jpeg图片生成并保存在本地

$size_x = 100;
$size_y = 100;

if(!isset($_GET['code'])) {
    $code = 'unknown';
}
$space_per_char = $size_x /(strlen($code)+1);

$img = imagecreatetruecolor($size_x,$size_y);
$background = imagecolorallocate($img,255,255,255);//白色
$border = imagecolorallocate($img,128,128,128);
$colors[] = imagecolorallocate($img,128,64,192);
$colors[] = imagecolorallocate($img,192,64,128);
$colors[] = imagecolorallocate($img,108,192,64);

for ($i = 0;$i <= 1;$i++) {
    $x1 = rand(5,$size_x - 5);
    $y1 = rand(5,$size_y - 5);
    $x2 = $x1 - 4 + rand(0, 8);
    $y2 = $y1 - 4 + rand(0, 8);
    imageline($img, $x1, $y1, $x2, $y2, $colors[rand(0,count($colors)-1)]);
}
header('Content-Type:image/jpeg');
imagejpeg($img,'test.jpeg');

备注:在例子中还需要字体插件arial.ttf 可以在网上下载,并放到本地文件夹调用


mmy123456
376 声望17 粉丝

有项目请联系:15201970281(毛毛)