下面是一个简单的C++代码示例,用于将JPG图像转换为base64格式:

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <cstring>
#include <algorithm>
#include <cstdlib>

using namespace std;

const string base64_chars =
             "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
             "abcdefghijklmnopqrstuvwxyz"
             "0123456789+/";

string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
    string ret;
    int i = 0;
    int j = 0;
    unsigned char char_array_3[3];
    unsigned char char_array_4[4];

    while (in_len--) {
        char_array_3[i++] = *(bytes_to_encode++);
        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++)
                ret += 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);
        char_array_4[3] = char_array_3[2] & 0x3f;

        for (j = 0; (j < i + 1); j++)
            ret += base64_chars[char_array_4[j]];

        while ((i++ < 3))
            ret += '=';
    }

    return ret;
}

int main() {
    ifstream input("test.jpg", ios::binary);
    vector<unsigned char> buffer((istreambuf_iterator<char>(input)), istreambuf_iterator<char>());

    string base64_string = base64_encode(&buffer[0], buffer.size());

    cout << base64_string << endl;

    return 0;
}

此代码使用了一个名为base64_encode的函数,该函数接受两个参数:bytes_to_encodein_lenbytes_to_encode是一个指向要编码的字节数组的指针,in_len是字节数组的长度。该函数使用标准的base64编码算法将字节数组转换为字符串,并返回结果字符串。

main函数中,我们读取了一个名为test.jpg的二进制文件,并将其存储在一个名为buffer的向量中。然后,我们将这个向量传递给base64_encode函数,将其转换为base64字符串并将其打印到控制台上。

请注意,这个代码示例可能需要进行适当的修改以适应您的特定用例。例如,您可能需要更改文件路径或使用不同的文件读取方法

用c++写jpg图片转base64格式的代码

原文地址: https://www.cveoy.top/t/topic/eRuz 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录