c++ 读取图片转base64
2023-03-27
ChatGPT 以下是一个使用C++读取图像并将其转换为Base64字符串的示例代码:
#include <fstream>
#include <sstream>
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <string>
std::string encode64(const void* data, size_t len) {
static constexpr char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const unsigned char* bytes = static_cast<const unsigned char*>(data);
std::string result;
int i =0;
while (i < len) {
int pad =0;
int n = bytes[i++] <<16;
if (i < len) {
n |= bytes[i++] <<8;
} else {
pad++;
}
if (i < len) {
n |= bytes[i++];
} else {
pad++;
}
for (int j =0; j <4 - pad; j++) {
unsigned char c = static_cast<unsigned char>(alphabet[(n >>18) &0x3F]);
result += c;
n <<=6;
}
for (int j =0; j < pad; j++) {
result += '=';
}
}
return result;
}
std::string encode64(const std::string& str) {
return encode64(str.data(), str.size());
}
std::string readFile(const std::string& fileName) {
std::ifstream file(fileName, std::ios::binary | std::ios::ate);
if (!file) {
throw std::runtime_error("Failed to open file: " + fileName);
}
size_t fileSize = static_cast<size_t>(file.tellg());
std::vector<char> buffer(fileSize);
file.seekg(0, std::ios::beg);
if (!file.read(buffer.data(), fileSize)) {
throw std::runtime_error("Failed to read file: " + fileName);
}
return std::string(buffer.data(), fileSize);
}
int main() {
try {
std::string fileName = "test.png";
std::string imageData = readFile(fileName);
std::string base64Data = encode64(imageData);
std::cout << "Base64 data: " << base64Data << std::endl;
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
return1;
}
return0;
}此代码将读取名为“test.png”的PNG图像文件,并将其转换为Base64字符串。转换使用
encode64函数,该函数将输入数据分成3个8位字节块,并将每个块转换为4个6位字符,每个字符为Base64字符集中的一个。如果输入数据大小不是3的倍数,该函数将使用填充字符“=”。读取文件的代码使用
readFile函数,该函数将文件读入内存缓冲区并返回一个std::string对象。请注意,此代码使用二进制模式打开文件,以便正确读取图像数据。
发表评论: