mirror of
https://github.com/lepture/captcha.git
synced 2026-03-13 09:43:22 +08:00
98 lines
2.3 KiB
ReStructuredText
98 lines
2.3 KiB
ReStructuredText
:description: Learn how to generate image CAPTCHA in Python.
|
|
|
|
Image Captcha
|
|
=============
|
|
|
|
.. rst-class:: lead
|
|
|
|
Unleash captivating security with image CAPTCHA mastery.
|
|
|
|
----
|
|
|
|
This module is compatibile with Pillow 9.4.0+.
|
|
|
|
.. module:: captcha.image
|
|
:noindex:
|
|
|
|
Usage
|
|
-----
|
|
|
|
Generating image CAPTCHA with the :class:`ImageCaptcha` class is incredibly straightforward.
|
|
|
|
|
|
.. code-block:: python
|
|
|
|
from io import BytesIO
|
|
from captcha.image import ImageCaptcha
|
|
|
|
captcha = ImageCaptcha()
|
|
data: BytesIO = captcha.generate('ABCD')
|
|
|
|
The result image would be something like:
|
|
|
|
.. figure:: ./_static/image-demo.png
|
|
|
|
This image CAPTCHA is generated by above code
|
|
|
|
Fonts
|
|
-----
|
|
|
|
The ``ImageCaptcha`` library comes with one built-in font named "DroidSansMono",
|
|
which is licensed under the Apache License 2.0. However, it is recommended to use
|
|
your own custom fonts for generating CAPTCHA images.
|
|
|
|
.. code-block:: python
|
|
|
|
custom_fonts = ['path/to/your/custom_font.ttf']
|
|
captcha = ImageCaptcha(fonts=[custom_fonts])
|
|
|
|
On the fly
|
|
----------
|
|
|
|
Let's explore how to use the CAPTCHA library to dynamically render image
|
|
CAPTCHAs within a Flask application. This allows you to generate CAPTCHA
|
|
images dynamically and serve them directly to users when they access a
|
|
specific endpoint.
|
|
|
|
.. code-block:: python
|
|
|
|
from flask import Flask, Response
|
|
from captcha.image import ImageCaptcha
|
|
|
|
image = ImageCaptcha()
|
|
app = Flask(__name__)
|
|
|
|
@app.route("/captcha")
|
|
def captcha_view():
|
|
# add your own logic to generate the code
|
|
code = "ABCD"
|
|
data = image.generate(code)
|
|
return Response(data, mimetype="image/png")
|
|
|
|
Character Settings
|
|
------------------
|
|
|
|
.. versionadded:: 0.6
|
|
|
|
Update the default settings to change the character renderring.
|
|
|
|
.. code-block:: python
|
|
|
|
from captcha.image import ImageCaptcha
|
|
|
|
captcha = ImageCaptcha()
|
|
captcha.character_rotate = (-40, 40)
|
|
captcha.generate("ABCD")
|
|
|
|
Available options:
|
|
|
|
.. code-block:: python
|
|
|
|
character_offset_dx: tuple[int, int] = (0, 4)
|
|
character_offset_dy: tuple[int, int] = (0, 6)
|
|
character_rotate: tuple[int, int] = (-30, 30)
|
|
character_warp_dx: tuple[float, float] = (0.1, 0.3)
|
|
character_warp_dy: tuple[float, float] = (0.2, 0.3)
|
|
word_space_probability: float = 0.5
|
|
word_offset_dx: float = 0.25
|