1. 程式人生 > >Python圖片處理 生產4位驗證碼

Python圖片處理 生產4位驗證碼

color class ext string int 填充 分享圖片 www 背景

圖像處理是一門應用非常廣的技術,而擁有非常豐富第三方擴展庫的 Python 當然不會錯過這一門盛宴。PIL (Python Imaging Library)是 Python 中最常用的圖像處理庫,如果你是python2.x,可以通過以下地址進行下載:http://www.pythonware.com/products/pil/index.htm,找到相對應的版本進行下載就可以了。
註意:PIL模塊在python3.x中已經替換成pillow模塊,文檔地址:http://pillow.readthedocs.io/en/latest/,直接使用pip3 install pillow即可安裝模塊,導入時使用from PIL import Image.

1利用PIL模塊生產4位驗證碼

代碼:

#!/usr/bin/env python 
#coding:utf8
import random
import string
import sys
import math
from PIL import Image, ImageDraw, ImageFont, ImageFilter

class VerificationCode():
    def __init__(self):
        # 字體的位置,不同版本的系統會有不同
        self.font_path = msyh.ttf
        # 生成幾位數的驗證碼
        self.number 
= 4 # 生成驗證碼圖片的高度和寬度 self.size = (100, 30) # 背景顏色,默認為白色 self.bgcolor = (255, 255, 255) # 字體顏色,默認為藍色 self.fontcolor = (0, 0, 255) # 幹擾線顏色。默認為紅色 self.linecolor = (255, 0, 0) # 是否要加入幹擾線 self.draw_line = True # 加入幹擾線條數的上下限 self.line_number
= 20 #驗證碼內容 self.text = "" # 用來隨機生成一個字符串 def gene_text(self): source = list(string.ascii_letters) for index in range(0, 10): source.append(str(index)) self.text = "".join(random.sample(source, self.number)) # number是生成驗證碼的位數 # 用來繪制幹擾線 def gene_line(self,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=self.linecolor) # 生成驗證碼 def gene_code(self): width, height = self.size # 寬和高 image = Image.new(RGBA, (width, height), self.bgcolor) # 創建圖片 font = ImageFont.truetype(self.font_path, 25) # 驗證碼的字體 draw = ImageDraw.Draw(image) # 創建畫筆 # text = self.gene_text() # 生成字符串 print(self.text) font_width, font_height = font.getsize(self.text) draw.text(((width - font_width) / self.number, (height - font_height) / self.number), self.text, font=font, fill=self.fontcolor) # 填充字符串 if self.draw_line: for i in range(self.line_number): self.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("{0}.png".format(self.text),"png") # 保存驗證碼圖片 # image.show() def main(): vc = VerificationCode() vc.gene_text() vc.gene_code() if __name__ == "__main__": main()

運行結果:

技術分享圖片

Python圖片處理 生產4位驗證碼