import random
from PIL import Image, ImageDraw, ImageFont, ImageFilter
from io import BytesIO
# 生成驗證碼圖片的高度和寬度
size = (129, 53)
# 背景顏色,默認為白色
bg_color = (255, 255, 255)
# 干擾線顏色。默認為紅色
linecolor = (0, 0, 0)
# 是否要加入干擾線
draw_line = True
# 加入干擾線條數的上下限
line_number = (1, 5)
# 隨機色
def getRandomColor():
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
return (r, g, b)
# 數字 小寫 大寫 里隨機一個
def getRandomChar():
random_num = str(random.randint(0, 9))
random_lower = chr(random.randint(97, 122))
random_upper = chr(random.randint(65, 90))
random_char = random.choice([random_num, random_lower, random_upper])
return random_char
# 用來繪制干擾線
def gene_line(draw, width, height):
begin = (random.randint(0, width), random.randint(0, height))
end = (random.randint(0, width), random.randint(0, height))
# begin = (0, random.randint(0, height)) # 起點
# end = (74, random.randint(0, height)) # 終點
linecolor = getRandomColor()
while linecolor == bg_color:
linecolor = getRandomColor()
draw.line([begin, end], fill=linecolor, width=random.choice(range(1, 3)))
# number驗證碼位數
def getcode(number=4):
width, height = size # 寬和高
# 背景色
bg_color = getRandomColor()
image = Image.new('RGBA', size, bg_color) # 創建圖片
import os
path = os.path.join(os.getcwd(), 'utils', 'Arial.ttf')
print(os.path.exists(path), '0-----------')
font = ImageFont.truetype(font='arial.ttf', size=36) # 驗證碼的字體
draw = ImageDraw.Draw(image) # 創建畫筆
text = ''
# 隨機的字符、顏色
for i in range(number):
code = getRandomChar()
code_color = getRandomColor()
while code_color == bg_color:
code_color = getRandomColor()
# 字體的大小
# font_width, font_height = font.getsize(code)
# 根據坐標填充字符
draw.text((10 + 30 * i, 3), code,
font=font, fill=code_color) # 填充字符串
text = text + code
if draw_line:
gene_line(draw, width, height)
# image = image.transform((width + 30, height + 10), Image.AFFINE, (1, -0.3, 0, -0.1, 1, 0), Image.BILINEAR) # 創建扭曲
# 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) # 濾鏡,邊界加強
bytes = BytesIO() # 內存
image.save(bytes, format='png') # 保存驗證碼圖片
return bytes.getvalue(), text # 獲得二進制數據,