Home > Backend Development > Python Tutorial > pythonPIL module and method of randomly generating Chinese verification codes

pythonPIL module and method of randomly generating Chinese verification codes

高洛峰
Release: 2017-03-07 16:16:29
Original
1505 people have browsed it

What we are going to learn today is how to use Python to generate a random Chinese verification code and save the image in .jpeg format. Friends who need it can refer to it

Before this, you must first understand PIL library in Python. PIL is the abbreviation of Python Imaging Library. PIL is a Python library for image processing. It provides a series of modules and methods, such as: cropping, translation, rotation, changing size, etc. In the PIL library, any image is represented by an Image object, so to load an image, the simplest form is as follows:

from PIL import Image
image = Image.open("1.jpeg")
Copy after login

In the PIL library, the most commonly used modules are Image, ImageDraw, ImageEnhance, ImageFile, etc.
The download address of PIL is: http://www.pythonware.com/products/pil/

Next, learn some common operations in PIL:

(1) Change the picture size

from PIL import Image

image = Image.open("1.jpeg")
new_img = image.resize((256,256),Image.BILINEAR)
new_img.save("2.jpeg")
Copy after login

(2) Rotate the picture

from PIL import Image

image = Image.open("1.jpeg")
new_img = image.rotate(45)
new_img.save("2.jpeg")
Copy after login

(3) Straight line drawing

The ImageDraw module in the PIL library provides basic functions of graphics drawing, which can draw straight lines, arcs, ellipses, rectangles, etc.

from PIL import Image,ImageDraw

image = Image.open("2.jpeg")
draw = ImageDraw.Draw(image)
width,height = image.size
draw.line(((0,0),(width-1,height-1)),fill=255)
draw.line(((0,height-1),(width-1,0)),fill=255)
image.save("2.jpeg")
Copy after login

(4) Draw a circle

from PIL import Image,ImageDraw

image = Image.open("2.jpeg")
draw = ImageDraw.Draw(image)
width,height = image.size
draw.arc((0,0,width-1,height-1),0,360,fill=255)
image.save("2.jpeg")
Copy after login

More methods are available See help documentation.


Now let’s study how to use Python to generate Chinese verification codes. In fact, this question is simple. We all know that the verification code is generally used to prevent network machine

people from using unlimited login attempts to crack the password. Then we need to randomly generate Chinese characters for this picture to verify. Generally speaking The word

in the picture will appear very blurry, which effectively prevents robot recognition. So in addition to randomly generating Chinese characters, we also need to add some interference lines and so on.

# -*- coding: utf-8 -*-
from PIL import Image,ImageDraw,ImageFont
import random
import math, string 

class RandomChar():
 @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(&#39;hex&#39;).decode(&#39;gb2312&#39;) 

class ImageChar:
 def __init__(self, fontColor = (0, 0, 0),
           size = (100, 40),
           fontPath = &#39;SIMSUN.TTC&#39;,
           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(&#39;RGB&#39;, 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)

 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())

 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)

ic = ImageChar(fontColor=(100,211, 90))
ic.randChinese(4)
ic.save("1.jpeg")
Copy after login

Running results:

pythonPIL module and method of randomly generating Chinese verification codes

More pythonPIL modules and randomly generated Chinese verification codes For method-related articles, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template