最近需要做一個驗證碼的功能寥掐,在網(wǎng)上找了許多資料,都是一些靜態(tài)的驗證碼圖片汉额,即都是png或jpg的圖片曹仗。于是,借鑒網(wǎng)上的一些資料蠕搜,弄一個gif的驗證碼圖片怎茫,現(xiàn)分享給大家。
所需依賴如下:
pip3 install pillow
pip3 install imageio
完整代碼如下:
import os
import random
from io import BytesIO
import imageio
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
class GifCodeImage(object):
def __init__(self, width=150, height=30, code_count=4, font_size=32, point_count=20, line_count=3, frame_count=30):
"""
:param width: 圖片寬度
:param height: 圖片高度
:param code_count: 驗證碼位數(shù)
:param font_size: 字體大小
:param point_count: 噪點數(shù)量
:param line_count: 噪線數(shù)量
:param frame_count: gif的幀數(shù)
"""
self.width = width
self.height = height
self.code_count = code_count
self.font_size = font_size
self.point_count = point_count
self.line_count = line_count
self.frame_count = frame_count
@staticmethod
def get_random_color():
"""
獲取一個隨機(jī)顏色(r,g,b)格式的
:return:
"""
c1 = random.randint(0, 255)
c2 = random.randint(0, 255)
c3 = random.randint(0, 255)
return c1, c2, c3
@staticmethod
def get_random_str():
"""
獲取一個隨機(jī)字符串妓灌,每個字符的顏色也是隨機(jī)的
:return:
"""
random_num = str(random.randint(0, 9))
random_low_alpha = chr(random.randint(97, 122))
random_upper_alpha = chr(random.randint(65, 90))
random_char = random.choice([random_num, random_low_alpha, random_upper_alpha])
return random_char
def get_code_and_image(self):
"""
生成驗證碼與動畫幀數(shù)
:return:
"""
code_str_list = []
for _ in range(self.code_count):
s = self.get_random_str()
code_str_list.append(s)
bg_color = self.get_random_color()
frame_list = []
for item in range(self.frame_count):
image = Image.new('RGB', (self.width, self.height), bg_color)
draw = ImageDraw.Draw(image)
path = os.path.join(os.getcwd(), "cabourgot-bold.otf")
font = ImageFont.truetype(path, size=self.font_size)
for i, code in enumerate(code_str_list):
v = random.randint(-7, 2)
x = random.randint(14, 22)
draw.text((x + i * 30, v), code, self.get_random_color(), font=font)
# 噪點噪線
# 劃線
for i in range(self.line_count):
x1 = random.randint(0, self.width)
x2 = random.randint(0, self.width)
y1 = random.randint(0, self.height)
y2 = random.randint(0, self.height)
draw.line((x1, y1, x2, y2), fill=self.get_random_color())
# 畫點
for i in range(self.point_count):
draw.point([random.randint(0, self.width), random.randint(0, self.height)],
fill=self.get_random_color())
x = random.randint(0, self.width)
y = random.randint(0, self.height)
draw.arc((x, y, x + 4, y + 4), 0, 90, fill=self.get_random_color())
f = BytesIO()
image.save(f, "png")
data = f.getvalue()
f.close()
data = imageio.imread(data, format="png")
frame_list.append(data)
return frame_list, "".join(code_str_list)
if __name__ == "__main__":
img = GifCodeImage()
frame_list, code_str = img.get_code_and_image()
imageio.mimsave("code.gif", frame_list, 'GIF', duration=0.35)
print(code_str)
不多說轨蛤,效果如下: