共計 1177 個字符,預計需要花費 3 分鐘才能閱讀完成。
Python 中生成驗證碼的方法有多種,以下是其中一種常用的方法:
- 使用 Python 的 Pillow 庫來生成驗證碼圖像,然后將圖像保存或顯示出來。首先需要安裝 Pillow 庫,可以使用 pip 命令安裝:
pip install Pillow
。
下面是一個生成簡單數字驗證碼的示例代碼:
from PIL import Image, ImageDraw, ImageFont
import random
# 隨機生成 4 位驗證碼
def generate_code():
code = ''
for _ in range(4):
# 隨機生成數字
code += str(random.randint(0, 9))
return code
# 生成驗證碼圖像
def generate_image(code):
# 圖像大小和背景顏色
width, height = 120, 50
bg_color = (255, 255, 255)
# 創建圖像對象
image = Image.new('RGB', (width, height), bg_color)
draw = ImageDraw.Draw(image)
# 加載字體
font = ImageFont.truetype('arial.ttf', 36)
# 繪制驗證碼文字
text_width, text_height = draw.textsize(code, font=font)
x = (width - text_width) // 2
y = (height - text_height) // 2
draw.text((x, y), code, font=font, fill=(0, 0, 0))
# 繪制干擾線
for _ in range(6):
x1 = random.randint(0, width)
y1 = random.randint(0, height)
x2 = random.randint(0, width)
y2 = random.randint(0, height)
draw.line((x1, y1, x2, y2), fill=(0, 0, 0), width=2)
# 繪制噪點
for _ in range(100):
x = random.randint(0, width - 1)
y = random.randint(0, height - 1)
draw.point((x, y), fill=(0, 0, 0))
return image
# 生成驗證碼并保存圖像
code = generate_code()
image = generate_image(code)
image.save('code.jpg')
上述代碼使用了 Pillow 庫創建了一個大小為 120×50 像素的白色背景圖像,使用 Arial 字體繪制了隨機生成的 4 位數字驗證碼,并添加了干擾線和噪點。最后將生成的驗證碼圖像保存為 code.jpg 文件。
當然,驗證碼的生成方法還可以根據需求進行調整,例如可以生成字母 + 數字的驗證碼,或者增加更復雜的干擾元素等。
丸趣 TV 網 – 提供最優質的資源集合!
正文完