一个粗糙的验证码生成程序

<?php
  //变色的验证码
  $code = '<span style="color:rgb('.mt_rand(0,255).','.mt_rand(0,255).','.mt_rand(0,255).')">'.mt_rand(0,9).'</span>';
  $code .= '<span style="color:rgb('.mt_rand(0,255).','.mt_rand(0,255).','.mt_rand(0,255).')">'.mt_rand(0,9).'</span>';
  $code .= '<span style="color:rgb('.mt_rand(0,255).','.mt_rand(0,255).','.mt_rand(0,255).')">'.mt_rand(0,9).'</span>';
  $code .= '<span style="color:rgb('.mt_rand(0,255).','.mt_rand(0,255).','.mt_rand(0,255).')">'.mt_rand(0,9).'</span>';
  echo $code;
以下是Python语言生成验证码程序: ```python import random import string from PIL import Image, ImageDraw, ImageFont # 生成随机字符串 def generate_code(length=4): # 随机生成数字和字母 code_chars = string.ascii_letters + string.digits code = ''.join(random.sample(code_chars, length)) return code # 生成验证码图像 def generate_image(code): # 图像尺寸 width, height = 120, 50 # 创建图像对象 image = Image.new('RGB', (width, height), color=(255, 255, 255)) # 创建画笔对象 draw = ImageDraw.Draw(image) # 设置字体 font = ImageFont.truetype('arial.ttf', 36) # 绘制验证码 draw.text((10, 5), code, font=font, fill=(0, 0, 0)) # 添加干扰线 for i in range(10): x1 = random.randint(0, width) x2 = random.randint(0, width) y1 = random.randint(0, height) y2 = random.randint(0, height) draw.line((x1, y1, x2, y2), fill=(0, 0, 0)) # 添加干扰点 for i in range(100): x = random.randint(0, width) y = random.randint(0, height) draw.point((x, y), fill=(0, 0, 0)) # 保存图像 image.save('code.png') # 测试 code = generate_code() print(code) generate_image(code) ``` 程序中,生成随机字符串的函数`generate_code`使用了Python标准库中的`string`模块,其中包含了各种字符集,包括大小写字母和数字。`random.sample`函数用于从字符集中随机选择指定长度的字符,随机生成验证码字符串。 生成验证码图像的函数`generate_image`使用了Python第三方库Pillow(也称Python Imaging Library,简称PIL),它提供了丰富的图像处理功能。函数中首先创建了一个白色背景的图像对象,然后使用`ImageDraw`模块创建画笔对象,设置了字体,并在图像上绘制了验证码。接着添加了干扰线和干扰点,增加了验证码的安全性。最后,将生成的图像保存到本地。 在测试代码中,先生成随机验证码字符串,然后调用`generate_image`函数生成图像,并将验证码字符串输出到控制台。程序生成验证码图像保存为`code.png`文件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值