python生成隨機(jī)驗(yàn)證碼(中文驗(yàn)證碼)示例
# -*- coding: utf-8 -*-
import Image,ImageDraw,ImageFont
import random
import math, string
class RandomChar():
"""用于隨機(jī)生成漢字"""
@staticmethod
def Unicode():
val = random.randint(0x4E00, 0x9FBF)
return unichr(val)
@staticmethod
def GB2312():
head = random.randint(0xB0, 0xCF)
body = random.randint(0xA, 0xF)
tail = random.randint(0, 0xF)
val = ( head << 8 ) | (body << 4) | tail
str = "%x" % val
return str.decode('hex').decode('gb2312')
class ImageChar():
def __init__(self, fontColor = (0, 0, 0),
size = (100, 40),
fontPath = 'wqy.ttc',
bgColor = (255, 255, 255),
fontSize = 20):
self.size = size
self.fontPath = fontPath
self.bgColor = bgColor
self.fontSize = fontSize
self.fontColor = fontColor
self.font = ImageFont.truetype(self.fontPath, self.fontSize)
self.image = Image.new('RGB', size, bgColor)
def rotate(self):
self.image.rotate(random.randint(0, 30), expand=0)
def drawText(self, pos, txt, fill):
draw = ImageDraw.Draw(self.image)
draw.text(pos, txt, font=self.font, fill=fill)
del draw
def randRGB(self):
return (random.randint(0, 255),
random.randint(0, 255),
random.randint(0, 255))
def randPoint(self):
(width, height) = self.size
return (random.randint(0, width), random.randint(0, height))
def randLine(self, num):
draw = ImageDraw.Draw(self.image)
for i in range(0, num):
draw.line([self.randPoint(), self.randPoint()], self.randRGB())
del draw
def randChinese(self, num):
gap = 5
start = 0
for i in range(0, num):
char = RandomChar().GB2312()
x = start + self.fontSize * i + random.randint(0, gap) + gap * i
self.drawText((x, random.randint(-5, 5)), RandomChar().GB2312(), self.randRGB())
self.rotate()
self.randLine(18)
def save(self, path):
self.image.save(path)
相關(guān)文章
Python導(dǎo)入或執(zhí)行python源文件的3種方法
這篇文章主要給大家介紹了關(guān)于Python導(dǎo)入或執(zhí)行python源文件的3種方法,python源代碼的文件以"py"為擴(kuò)展名,由python.exe解釋,可以在控制臺(tái)下運(yùn)行,需要的朋友可以參考下2023-08-08Django drf使用Django自帶的用戶系統(tǒng)的注冊功能
本文主要介紹了Django drf使用Django自帶的用戶系統(tǒng)的注冊功能,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02詳解python如何在django中為用戶模型添加自定義權(quán)限
這篇文章主要介紹了python如何在django中為用戶模型添加自定義權(quán)限,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-10-10Python中pillow知識(shí)點(diǎn)學(xué)習(xí)
本文給大家通過一篇Python中pillow知識(shí)點(diǎn)學(xué)習(xí)的筆記內(nèi)容讓大家對pillow有一個(gè)學(xué)習(xí)方向的有一個(gè)認(rèn)識(shí),有興趣的朋友學(xué)習(xí)下。2018-04-04python定時(shí)任務(wù)sched庫用法簡單實(shí)例
sched可用于定時(shí)任務(wù),唯一需要注意的就是,這些任務(wù)在一個(gè)線程中運(yùn)行,如果前面的任務(wù)耗時(shí)過長,則后面的任務(wù)將順延執(zhí)行,下面這篇文章主要給大家介紹了關(guān)于python定時(shí)任務(wù)sched庫用法的相關(guān)資料,需要的朋友可以參考下2023-01-01