欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 能源 > Python生成图形验证码

Python生成图形验证码

2025/9/14 11:58:31 来源:https://blog.csdn.net/YQ20210216/article/details/140022643  浏览:    关键词:Python生成图形验证码

文章目录

  • 安装pillow
  • 基本用法
  • 生成代码

安装pillow

pip install pillow

基本用法

特殊字体文字

如下所示,将下载下来的ttf字体文件放到py文件同一文件夹下

分享一个免费下载字体网站:http://www.webpagepublicity.com/free-fonts.html
我选的字体是Bajoran Regular.ttf

# 第一个参数:表示字体文件路径
# 第二个参数:表示字体大小
font = ImageFont.truetype("Bajoran Regular.ttf", 28)
# 第一个参数:表示起始坐标
# 第二个参数:表示写入内容
# 第三个参数:表示颜色
# 第四个参数:表示颜色
draw.text([0, 0], 'python', "red", font=font)

生成图片

from PIL import Image
img = Image.new(mode='RGB', size=(120, 30), color=(255, 255, 255))# 在图片查看器中查看
img.show()# 保存到本地
with open('code.png', 'wb') as f:img.save(f, format='png')

操作画笔

#开始画画
img = Image.new(mode='RGB', size=(120, 30), color=(255, 255, 255))
draw = ImageDraw.Draw(img, mode='RGB')# 第一个参数表示坐标,第二个参数表示颜色
draw.point([100, 100], fill="red")
draw.point([300, 300], fill=(255, 255, 255))# 第一个参数表示起始坐标和结束坐标,第二个参数表示颜色
draw.line((100, 100, 100, 100), fill="red")
draw.line((100, 100, 300, 100), fill=(255, 255, 255))# 第一个参数:表示起始坐标和结束坐标(圆要画在其中间)
# 第二个参数:表示开始角度
# 第三个参数:表示结束角度
# 第四个参数:表示颜色
draw.arc((100,100,300,300),0,90,fill="red")

生成代码

import random
from PIL import Image, ImageDraw, ImageFont, ImageFilter# 生成默认含4个字符验证码的图片
def check_code(width=120, height=30, char_length=4, font_file='Bajoran Regular.ttf', font_size=28):code = []img = Image.new(mode='RGB', size=(width, height), color=(255, 255, 255))draw = ImageDraw.Draw(img, mode='RGB')def rndChar():"""生成随机大小写字母:return:"""up_or_low = random.randint(0, 1)if up_or_low == 0:return chr(random.randint(97, 122))return chr(random.randint(65, 90))def rndColor():"""生成随机颜色:return:"""return (random.randint(0, 255), random.randint(10, 255), random.randint(64, 255))# 写文字font = ImageFont.truetype(font_file, font_size)for i in range(char_length):char = rndChar()code.append(char)h = random.randint(0, 4)draw.text([i * width / char_length, h], char, font=font, fill=rndColor())# 写干扰点for i in range(40):draw.point([random.randint(0, width), random.randint(0, height)], fill=rndColor())# 写干扰圆圈for i in range(40):draw.point([random.randint(0, width), random.randint(0, height)], fill=rndColor())x = random.randint(0, width)y = random.randint(0, height)draw.arc((x, y, x + 4, y + 4), 0, 90, fill=rndColor())# 画干扰线for i in range(5):x1 = random.randint(0, width)y1 = random.randint(0, height)x2 = random.randint(0, width)y2 = random.randint(0, height)draw.line((x1, y1, x2, y2), fill=rndColor())img = img.filter(ImageFilter.EDGE_ENHANCE_MORE)return img, ''.join(code)if __name__ == '__main__':img, code_str = check_code()print(code_str)with open('code.png', 'wb') as f:img.save(f, format='png')

运行结果
在这里插入图片描述

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词