以下是C++代码,用于将JPEG图像转换为Base64编码:

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

const char base64_table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

std::string base64_encode(const unsigned char* data, size_t size) {
    std::ostringstream oss;
    unsigned char buffer[4];
    size_t i = 0;
    while (i < size) {
        buffer[0] = data[i] >> 2;
        buffer[1] = ((data[i] & 0x03) << 4) | ((data[i + 1] & 0xf0) >> 4);
        buffer[2] = ((data[i + 1] & 0x0f) << 2) | ((data[i + 2] & 0xc0) >> 6);
        buffer[3] = data[i + 2] & 0x3f;
        for (size_t j = 0; j < 4; j++) {
            if (i + j <= size) {
                oss << base64_table[buffer[j]];
            }
            else {
                oss << '=';
            }
        }
        i += 3;
    }
    return oss.str();
}

int main() {
    std::ifstream ifs("test.jpg", std::ios::binary);
    if (!ifs) {
        std::cerr << "Cannot open file" << std::endl;
        return 1;
    }
    std::vector<unsigned char> data((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>());
    ifs.close();

    std::string encoded_data = base64_encode(data.data(), data.size());
    std::cout << encoded_data << std::endl;

    return 0;
}

此代码将读取名为“test.jpg”的JPEG图像文件,并将其转换为Base64编码。要使用其他文件,请将文件名更改为相应的文件名。

该程序使用“base64_encode”函数将二进制数据转换为Base64编码。该函数使用标准Base64编码表将三个8位字节的块编码为四个6位字符的块。如果最后的块不足三个字节,则它将使用填充字符“=”填充

用c++写jpg转base64

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

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