Github官方倉庫
https://github.com/lepture/captcha
使用方法
安裝輪子
pip install captcha
調用過程
import base64
import random
import string
from io import BytesIO
from captcha.image import ImageCaptcha
image = ImageCaptcha(
# 寬度
width=180,
# 高度
height=80,
# 加載自定義的ttf格式字體(可以加載多個字體)
fonts=['./chn.ttf'],
# 字體大小隨機從傳入的元組中獲取
font_sizes=(60, 80, 100)
)
# 生成隨機4位數字
code = ''.join(random.sample(string.digits, 4))
# 生成Image對象
im = image.generate_image(code)
# 本地打開預覽測試
im.show()
# 轉成base64編碼的字符串
buff = BytesIO()
im.save(buff, format='png')
im_str = base64.b64encode(buff.getvalue())
print(im_str)