PHP使用GD库画简单的验证码

使用PHP GD库(Graphic Device)绘制简单的页面验证码

有注释:

<?php
$img=imagecreatetruecolor(100,50);//定义画布
$red=imagecolorallocate($img,0xFF,0x00,0x00);//定义颜色
$black=imagecolorallocate($img,0x00,0x00,0x00);
$green=imagecolorallocate($img,0x00,0xFF,0x00);
$bg=imagecolorallocate($img,0xAC,0xAC,0xB6);
header("content-type: image/png");//header 和imagefill用来图像输出
imagefill($img,0,0,$bg);
//随机生成数字
$code='';
for($i=0;$i<4;$i++){
$code.=rand(0,9);
}
//生成随机点
for($i=0;$i<50;$i++){
imagesetpixel($img,rand(0,100),rand(0,100),$green);//画点
imagesetpixel($img,rand(0,100),rand(0,100),$red);
imagesetpixel($img,rand(0,100),rand(0,100),$black);
}
//画字符串
imagestring($img,30,30,15,$code,$black);
imagepng($img);//输出图像,imagepng($img,'path');保存到文件
imagedestroy($img);//销毁

效果图:


PHP GD是一个用于处理图像的强大,它不仅可以用来创建、修改和输出静态图片,还可以用来动态生成图像,包括绘制表格。要在PHP中利用GD库画表格,你可以使用`imagecreatetruecolor()`函数创建一个新的图像,然后通过`imagesetpixel()`或`imagefilledrectangle()`等函数绘制线条和填充区域。 以下是一个简单的例子,展示如何使用GD画一个简单的二维表格: ```php <?php // 创建新图像 $width = 400; $height = 300; $image = imagecreatetruecolor($width, $height); // 设置背景颜色 $bg_color = imagecolorallocate($image, 255, 255, 255); imagefill($image, 0, 0, $bg_color); // 设置单元格边框的颜色和宽度 $cell_border_color = imagecolorallocate($image, 0, 0, 0); $cell_border_width = 1; // 绘制表格行和列 for ($row = 0; $row < 5; $row++) { for ($col = 0; $col < 5; $col++) { // 计算每个单元格的坐标 $x1 = $col * 80 + 10; $y1 = $row * 60 + 10; $x2 = $col * 80 + 90; $y2 = $row * 60 + 50; // 绘制边框 imageline($image, $x1, $y1, $x2, $y2, $cell_border_color, $cell_border_width); // 如果不是第一行也不是最后一列,填充单元格 if ($row > 0 && $row < 4 && $col > 0 && $col < 4) { imagesetpixel($image, $x1 + 5, $y1 + 5, $cell_border_color); imagesetpixel($image, $x1 + 5, $y2 - 5, $cell_border_color); imagesetpixel($image, $x2 - 5, $y1 + 5, $cell_border_color); imagesetpixel($image, $x2 - 5, $y2 - 5, $cell_border_color); } } } // 输出或保存图像 header('Content-Type: image/png'); imagepng($image); imagedestroy($image); // 关闭资源 ?>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值