| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 | <?php
namespace App\Service;
class CaptchaService
{
    public function generateCode(): string
    {
        $characters = ['2', '3', '4', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v','x', 'y', 'z'];
        $code = '';
        $max = count($characters) - 1;
        for ($i = 0; $i < 6; $i++) {
            $code .= $characters[random_int(0, $max)];
        }
        return $code;
    }
    public function generateImage(string $code): string
    {
        // Create image
        $width = 200;
        $height = 50;
        $image = imagecreatetruecolor($width, $height);
        // Colors
        $background = imagecolorallocate($image, 255, 255, 255);
        $textColor = imagecolorallocate($image, 33, 33, 33);
        $noiseColor = imagecolorallocate($image, 123, 123, 123);
        // Fill background
        imagefilledrectangle($image, 0, 0, $width, $height, $background);
        // Add random lines for noise
        for ($i = 0; $i < 4; $i++) {
            imageline(
                $image,
                mt_rand(0, $width),
                mt_rand(0, $height),
                mt_rand(0, $width),
                mt_rand(0, $height),
                $noiseColor
            );
        }
        // Add dots for noise
        for ($i = 0; $i < 100; $i++) {
            imagesetpixel(
                $image,
                mt_rand(0, $width),
                mt_rand(0, $height),
                $noiseColor
            );
        }
        // Split code into characters and space them out
        $chars = str_split($code);
        $spacing = 25; // Space between characters
        $startX = 30;  // Starting X position
        foreach ($chars as $i => $char) {
            imagestring(
                $image,
                5, // font size (1-5)
                $startX + ($i * $spacing),
                15, // Y position
                $char,
                $textColor
            );
        }
        // Output image as base64
        ob_start();
        imagepng($image);
        $imageData = ob_get_clean();
        // Clean up
        imagedestroy($image);
        return 'data:image/png;base64,' . base64_encode($imageData);
    }
}
 |