python生成4位验证码_Python 生成4位验证码图片
import random
import string
from PIL import Image,ImageDraw,ImageFont,ImageFilter
# 字體的位置
font_path = "/Library/Fonts/Arial.ttf"
# 驗證碼的位數
number = 4
# 生成圖片的大小
size = (100,30)
# 圖片背景顏色-白色
bgcolor = (255,255,255)
# 驗證碼字體顏色——藍色
fontcolor = (0,0,255)
# 干擾線的顏色——紅色
linecolor = (255,0,0)
# 是否加入干擾線
draw_line = True
# 圖片上干擾線的顏色
line_number = (1,5)
def gene_text():
# 獲取26個英文字母
source = list(string.ascii_letters)
for index in range(0, 10):
# 獲取10個數字
source.append(str(index))
return ''.join(random.sample(source, number)) # number是生成驗證碼的位數
#用來繪制干擾線
def gene_line(draw,width,height):
begin = (random.randint(0, width), random.randint(0, height))
end = (random.randint(0, width), random.randint(0, height))
draw.line([begin, end], fill = linecolor)
#生成驗證碼
def gene_code(k):
# 寬和高
width,height = size
# 創建圖片
image = Image.new('RGBA',(width,height),bgcolor)
# 驗證碼的字體
font = ImageFont.truetype(font_path,25)
# 創建畫筆
draw = ImageDraw.Draw(image)
# 生成字符串
text = gene_text()
font_width, font_height = font.getsize(text)
# 填充字符串
draw.text(((width - font_width) / number, (height - font_height) / number),text,\
font= font,fill=fontcolor)
if draw_line:
gene_line(draw,width,height)
# 創建扭曲
image = image.transform((width+20,height+10), Image.AFFINE, (1,-0.3,0,-0.1,1,0),Image.BILINEAR)
# 濾鏡,邊界加強
image = image.filter(ImageFilter.EDGE_ENHANCE_MORE)
# 保存驗證碼圖片
image.save('%d.png'%k)
if __name__ == "__main__":
# 循環創建驗證碼圖片
for i in range(0,1000):
gene_code(i)
總結
以上是生活随笔為你收集整理的python生成4位验证码_Python 生成4位验证码图片的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《大数据》2021年第4期目次摘要
- 下一篇: 可视化:在窗口中显示一个球,该球以与水平