python show-me-the-code 第0010題

第 0010 題:使用 Python 生成類似於下圖中的字母驗證碼圖片

字母驗證碼

分析:畫圖,隨機字母,顏色

模塊:PIL,random


代碼如下:

from PIL import Image,ImageDraw,ImageFont,ImageFilter
import random

def rndColor():  #產生隨機顏色
	return (random.randint(64,255),random.randint(64,255),random.randint(64,255))

def rndChar():  #產生隨機字母
	return chr(random.randint(65,90))
def rndColor2(): 
	return (random.randint(30,120),random.randint(30,120),random.randint(30,120))

height=60
width=240
image=Image.new('RGB',(width,height),(255,255,255))  #白色畫布
font=ImageFont.truetype("Arial.ttf",36)        #畫筆字體
draw=ImageDraw.Draw(image)   #繪畫對象
for i in range(width):
	for j in range(height):
		draw.point((i,j),fill=rndColor())     #隨機逐像素填充顏色

for i in range(4):
	draw.text((60*i+10,10),rndChar(),font=font,fill=rndColor2())  #文本繪畫

image=image.filter(ImageFilter.BLUR)  #產生模糊感
image.save('code.jpg','jpeg')
image.show()


發佈了31 篇原創文章 · 獲贊 1 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章