Skip to content

Challenge Generator

Fabian Wennink edited this page Oct 31, 2023 · 2 revisions

A generator is responsible for generating challenge images and providing it back to the challenge processor. You may either use one of the provided generators, or implement your own if you wish to do so.

Provided generators

Generators for the GD and Imagick extensions are available by default. To use either of these generators, ensure that the GD extension or ImageMagick is installed and enabled for image processing.

The GD generator is located at \IconCaptcha\Challenge\Generators\GD::class, and the Imagick generator is located at \IconCaptcha\Challenge\Generators\Imagick::class.

The generator can be configured in the PHP configuration with the challenge.generator option.

'generator' => \IconCaptcha\Challenge\Generators\GD::class,

Custom generator

If you wish to create your own generator, ensure that your custom generator class extends the \IconCaptcha\Challenge\Image\AbstractImageGenerator class and implements all required functions. The AbstractImageGenerator base class implements the interface \IconCaptcha\Challenge\Image\ImageGeneratorInterface, which contains the function definitions which must be implemented.

use IconCaptcha\Challenge\Image\AbstractImageGenerator;

class YourGenerator extends AbstractImageGenerator
{
    public function loadImage(string $path)
    {
        // return ...;
    }

    // ...

    public function render($image): string
    {
        // ...

        return base64_encode($output);
    }
}

Function definitions

The following functions must be implemented in your custom challenge generator.

Function Description
loadImage(string $path) Returns an image resource/object containing the image at the given path.
flipHorizontal($image) Flips the given image horizontally.
flipVertical($image) Flips the given image vertically.
rotate($image, int $degree) Rotates the given image.
drawBorder($image, $color, int $x1, int $y1, int $x2, int $y2) Draws a line on the given image at the given coordinates.
drawIcon($image, $icon, int $x, int $y, int $size) Draws the given icon image onto the larger challenge image, at the given coordinates.
colorFromRGB($image, int $red, int $green, int $blue) Creates a color object. This object will be used by the drawBorder function.
render($image): string Outputs the given challenge image resource as a base64 string.