search
HomeBackend DevelopmentPython TutorialpythonPIL module and method of randomly generating Chinese verification codes

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

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

(2) Rotate the picture

from PIL import Image

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

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

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

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

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!

Statement
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
详细讲解Python之Seaborn(数据可视化)详细讲解Python之Seaborn(数据可视化)Apr 21, 2022 pm 06:08 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

详细了解Python进程池与进程锁详细了解Python进程池与进程锁May 10, 2022 pm 06:11 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

Python自动化实践之筛选简历Python自动化实践之筛选简历Jun 07, 2022 pm 06:59 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

归纳总结Python标准库归纳总结Python标准库May 03, 2022 am 09:00 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于标准库总结的相关问题,下面一起来看一下,希望对大家有帮助。

分享10款高效的VSCode插件,总有一款能够惊艳到你!!分享10款高效的VSCode插件,总有一款能够惊艳到你!!Mar 09, 2021 am 10:15 AM

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

Python数据类型详解之字符串、数字Python数据类型详解之字符串、数字Apr 27, 2022 pm 07:27 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

详细介绍python的numpy模块详细介绍python的numpy模块May 19, 2022 am 11:43 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。

python中文是什么意思python中文是什么意思Jun 24, 2019 pm 02:22 PM

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),