Using CImg to generate image captcha

Generate an image CAPTCHA containing alphanumeric characters (0-9, a-z, A-Z)
using only CImg, with specified height, width, and code length.

<pre class="prism-highlight prism-language-cpp">ylib::buffer make_code(uint32 width, uint32 height, uint32 code_length, std::string& captcha)
{
    // Create a white background image
    cimg_library::CImg<unsigned char> img(width, height, 1, 3, 255);

    // Initialize the random number generator
    std::random_device rd;  // Random number seed
    std::mt19937 gen(rd()); // Standard mersenne_twister_engine
    std::uniform_int_distribution<> distrib(0, 35);

    // Generate random captcha text
    const std::string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    for (uint32 i = 0; i < code_length; ++i) {
        captcha += letters[distrib(gen)];
    }

    // Calculate font size and position, draw text
    int fontSize = height / 2 + 5;
    int startX = (width - fontSize * code_length) / 2;
    int startY = (height - fontSize) / 2 + fontSize / 4;

    for (uint32 i = 0; i < code_length; ++i) {
        uint32 x = startX + i * fontSize;
        img.draw_text((int)x, startY, std::string(1, captcha[i]).c_str(), "black", 0, 1, fontSize);
    }

    // Save the image
    std::string tempfilepath = system::temp_path()
#ifdef _WIN32
        + "\\img_code_"
#else
        + "/img_code_"
#endif
        + std::to_string(system::random(9999999, 999999999));
    img.save_bmp(tempfilepath.c_str());
    ylib::buffer result;
    result = ylib::file::read(tempfilepath);
    ylib::file::remove(tempfilepath);
    return result;
}

Title of this article:<Using CImg to generate image captcha>Author:minimini
Original link:https://www.xxmjw.com/post/9.html
Unless otherwise specified, all content is original. Please indicate when reprinting.

Related

minimini

minimini