from captcha.image import ImageCaptcha
import random
import string
from PIL import Image
import io
# 生成随机字符的函数
def random_char(char_num=4):
return ''.join(random.choice(string.ascii_uppercase) for _ in range(char_num))
# 生成验证码图片
captcha_text = random_char()
print(captcha_text)
# 设置图像大小,例如 200x100 像素
width, height = 160, 80
# 创建 ImageCaptcha 对象时指定大小
image = ImageCaptcha(width=width, height=height)
# image = ImageCaptcha()
# 生成图片并写入文件
captcha_image = image.generate(captcha_text)
image.write(captcha_text, 'captcha.png')
# 将 BytesIO 对象转换为 PIL 图像对象
captcha_image = Image.open(io.BytesIO(captcha_image.getvalue()))
# 直接显示图片
# captcha_image.show()
【py】captcha验证码
最新推荐文章于 2024-07-25 14:09:24 发布