[Python] Python动态生成中文验证码 →→→→→进入此内容的聊天室

来自 , 2020-07-22, 写在 Python, 查看 107 次.
URL http://www.code666.cn/view/67fe0f66
  1. # -*- coding: utf-8 -*-
  2. import Image,ImageDraw,ImageFont
  3. import random
  4. import math, string  
  5.  
  6. class RandomChar():
  7.   """用于随机生成汉字"""
  8.   @staticmethod
  9.   def Unicode():
  10.     val = random.randint(0x4E00, 0x9FBF)
  11.     return unichr(val)  
  12.  
  13.   @staticmethod
  14.   def GB2312():
  15.     head = random.randint(0xB0, 0xCF)
  16.     body = random.randint(0xA, 0xF)
  17.     tail = random.randint(0, 0xF)
  18.     val = ( head << 8 ) | (body << 4) | tail
  19.     str = "%x" % val
  20.     return str.decode('hex').decode('gb2312')  
  21.  
  22. class ImageChar():
  23.   def __init__(self, fontColor = (0, 0, 0),
  24.                      size = (100, 40),
  25.                      fontPath = 'wqy.ttc',
  26.                      bgColor = (255, 255, 255),
  27.                      fontSize = 20):
  28.     self.size = size
  29.     self.fontPath = fontPath
  30.     self.bgColor = bgColor
  31.     self.fontSize = fontSize
  32.     self.fontColor = fontColor
  33.     self.font = ImageFont.truetype(self.fontPath, self.fontSize)
  34.     self.image = Image.new('RGB', size, bgColor)  
  35.  
  36.   def rotate(self):
  37.     self.image.rotate(random.randint(0, 30), expand=0)  
  38.  
  39.   def drawText(self, pos, txt, fill):
  40.     draw = ImageDraw.Draw(self.image)
  41.     draw.text(pos, txt, font=self.font, fill=fill)
  42.     del draw  
  43.  
  44.   def randRGB(self):
  45.     return (random.randint(0, 255),
  46.            random.randint(0, 255),
  47.            random.randint(0, 255))  
  48.  
  49.   def randPoint(self):
  50.     (width, height) = self.size
  51.     return (random.randint(0, width), random.randint(0, height))  
  52.  
  53.   def randLine(self, num):
  54.     draw = ImageDraw.Draw(self.image)
  55.     for i in range(0, num):
  56.       draw.line([self.randPoint(), self.randPoint()], self.randRGB())
  57.     del draw  
  58.  
  59.   def randChinese(self, num):
  60.     gap = 5
  61.     start = 0
  62.     for i in range(0, num):
  63.       char = RandomChar().GB2312()
  64.       x = start + self.fontSize * i + random.randint(0, gap) + gap * i
  65.       self.drawText((x, random.randint(-5, 5)), RandomChar().GB2312(), self.randRGB())
  66.       self.rotate()
  67.     self.randLine(18)  
  68.  
  69.   def save(self, path):
  70.     self.image.save(path)
  71.  
  72.  
  73. #//python/7363

回复 "Python动态生成中文验证码"

这儿你可以回复上面这条便签

captcha