Untitled

 avatar
unknown
plain_text
a year ago
2.6 kB
4
Indexable
#include <opencv2/opencv.hpp>
#include <iostream>
#include <fstream>
#include <vector>

// Function to encode data into base64
std::string base64_encode(const unsigned char* data, unsigned int data_length) {
    const std::string base64_chars = 
                 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                 "abcdefghijklmnopqrstuvwxyz"
                 "0123456789+/";

    std::string encoded_data;
    int i = 0;
    int j = 0;
    unsigned char char_array_3[3];
    unsigned char char_array_4[4];

    while (data_length--) {
        char_array_3[i++] = *(data++);
        if (i == 3) {
            char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
            char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
            char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
            char_array_4[3] = char_array_3[2] & 0x3f;

            for(i = 0; i < 4; i++) {
                encoded_data += base64_chars[char_array_4[i]];
            }
            i = 0;
        }
    }

    if (i) {
        for(j = i; j < 3; j++) {
            char_array_3[j] = '\0';
        }

        char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
        char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
        char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);

        for (j = 0; j < i + 1; j++) {
            encoded_data += base64_chars[char_array_4[j]];
        }

        while((i++ < 3)) {
            encoded_data += '=';
        }
    }

    return encoded_data;
}

std::string imageToBase64(const std::string& filename) {
    // Load an image
    cv::Mat image = cv::imread(filename);

    // Check if the image is loaded successfully
    if (image.empty()) {
        std::cerr << "Failed to load image " << filename << std::endl;
        return "";
    }

    // Convert the image to a vector of bytes
    std::vector<uchar> buffer;
    cv::imencode(".jpg", image, buffer);

    // Convert the vector of bytes to a Base64 string
    return base64_encode(buffer.data(), buffer.size());
}

int main(int argc, char *argv[]) {
    if (argc != 2) {
        std::cerr << "Usage: " << argv[0] << " <image_file>" << std::endl;
        return 1;
    }

    std::string filename(argv[1]);

    // Convert image to Base64
    std::string base64_image = imageToBase64(filename);

    // Print the Base64 string (or use it as needed)
    std::cout << "Base64 Encoded Image:\n" << base64_image << std::endl;

    return 0;
}
Editor is loading...
Leave a Comment