|
|
#include <iostream> |
|
|
#include <fstream> |
|
|
#include <vector> |
|
|
#include <string> |
|
|
|
|
|
|
|
|
static const std::string base64_chars = |
|
|
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; |
|
|
|
|
|
|
|
|
static inline bool is_base64(unsigned char c) { |
|
|
return (isalnum(c) || (c == '+') || (c == '/')); |
|
|
} |
|
|
|
|
|
|
|
|
std::string base64_encode(std::string pth_img) { |
|
|
|
|
|
|
|
|
std::ifstream file(pth_img, std::ios::binary); |
|
|
if (!file) { |
|
|
std::cerr << "无法打开文件: " << pth_img << std::endl; |
|
|
} |
|
|
|
|
|
|
|
|
const std::vector<unsigned char> data( |
|
|
(std::istreambuf_iterator<char>(file)), |
|
|
(std::istreambuf_iterator<char>()) |
|
|
); |
|
|
|
|
|
std::string ret; |
|
|
int i = 0; |
|
|
int j = 0; |
|
|
unsigned char char_array_3[3]; |
|
|
unsigned char char_array_4[4]; |
|
|
int data_size = data.size(); |
|
|
|
|
|
while (data_size--) { |
|
|
char_array_3[i++] = data[j++]; |
|
|
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; |
|
|
} |
|
|
|
|
|
|
|
|
std::vector<unsigned char> base64_decode(const std::string& input) { |
|
|
|
|
|
const std::string BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; |
|
|
|
|
|
std::vector<int> decode_table(256, -1); |
|
|
for (int i = 0; i < 64; i++) |
|
|
decode_table[BASE64_CHARS[i]] = i; |
|
|
|
|
|
std::vector<unsigned char> decoded; |
|
|
int val = 0, bits = -8; |
|
|
for (unsigned char c : input) { |
|
|
if (c == '=') break; |
|
|
if (decode_table[c] == -1) continue; |
|
|
|
|
|
val = (val << 6) + decode_table[c]; |
|
|
bits += 6; |
|
|
if (bits >= 0) { |
|
|
decoded.push_back((val >> bits) & 0xFF); |
|
|
bits -= 8; |
|
|
} |
|
|
} |
|
|
return decoded; |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|