SoFunction
Updated on 2024-11-15

Make and validate image captcha using PIL in python

CAPTCHA creation

The #string module comes with a collection of numeric, alphabetic, and special character variables, so we don't need to handwrite the collection.
import string
import random
import os
import uuid

import settings
from PIL import Image, ImageDraw, ImageColor, ImageFilter, ImageFont


class Code(object):
 # Generate randomly generated numbers or letters
 def random_hexdigits(self, len=1):
 return (, len)
 
 # Generate interfering characters
 def punctuation(self, len=1):
 return tuple((, len))
 
 # Define the interference character color
 def random_color(self, min=64, max=255):
 return tuple(((min, max) for i in range(3)))
 
 # Generate CAPTCHA
 def creat_code(self, width=80, height=24, color=(192, 192, 192)):
 image = ('RGB', (width, height), color)
 # Suggest downloading a few fonts to change the style, I defined the static path in the setting granule, so I'll just import it here.
 font = ((, 'fonts/'), 20)
 draw = (image)
 self.fill_color(draw, image, 5)
 self.fill_dischar(draw, image, 10)
 code = self.fill_char(draw, image, 4, 10, font)
 image_name = '{}.jpeg'.format(uuid.uuid4().hex)
 image_path = (, 'code/{}'.format(image_name))
 print(image_path)
 (image_path)
 return {'code': code, 'image_path': image_path}
 
 # Fill color
 def fill_color(self, draw, image, interval):
 for i in range(0, , interval):
  for j in range(0, , interval):
  ((i, j), fill=self.random_color())
 
 # Fill in CAPTCHA
 def fill_dischar(self, draw, image, interval):
 for i in range(0, , interval):
  dis = ()
  j = (3,  - 3)
  ((i, j), dis[0], fill=self.random_color(64, 255))
 
 # Fill in CAPTCHA
 def fill_char(self, draw, image, num, interval, font):
 code = ''
 for i in range(num):
  cha = self.random_hexdigits()
  code += str(cha[0])
  j = (0, 5)
  # print(cha)
  # print(*(i/num)+interval,j)
  (( * (i / num) + interval, j), cha[0], fill=self.random_color(32, 127), font=font)
 return code


if __name__ == "__main__":
 code = Code()
 print(code.creat_code())

flask routing configuration

import os
from flask import Flask, Response
from flask import render_template
from  import Code

app = Flask(__name__)


@('/')
def Register():
 return render_template('')


@('/codes/')
def code():
 infor = Code().creat_code()
 image_path = infor["image_path"]
 code = infor['code']
 
 print(image_path)
 with open(image_path, 'rb') as f:
  image_content = ()
 (image_path)
 return Response(image_content, mimetype='jpeg')


if __name__ == '__main__':
 (debug=True)

Front-end configuration

 <div class='form-row'>
   <form  method="post" autocomplete="off">
    <div class="form-group ">
     <label>post (office)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;chest</label>
     <input type="text"  name="email" value="None" placeholder="Please enter your e-mail address."/>
    </div>
    <div class="form-group ">
     <label>name of an ancient state&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;classifier for length or distance (yard), happenings etc</label>
     <input type="password"  name="password" value="None" placeholder="Please enter a password of 6-20 non-Chinese characters."/>
    </div>
    <div class="form-group captcha1 ">
     <label>test&nbsp;proof&nbsp;classifier for length or distance (yard), happenings etc</label>
     <img src="/codes/" alt="captcha" title="Click to switch." class="captcha"
       onclick="='codes/?'+()"/>
     <input autocomplete="off"  name="captcha_1" height="30px" type="text">
    </div>
    <input class="btn btn-green"  type="submit" value="Register."/>
   </form>

Source code sharing:/geekdick/pythonDemo/tree/master/verify