参考:
由于只需要编码算法,所及将cpp-base64库中的编码函数单独拿出来,代码如下:
#include <string>
// 声明
std::string base64_encode(unsigned char const* bytes_to_encode, size_t in_len, bool url = false);
static const char* base64_chars[2] = {
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789"
"+/",
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789"
"-_"};
// 定义
std::string base64_encode(unsigned char const* bytes_to_encode, size_t in_len, bool url) {
size_t len_encoded = (in_len +2) / 3 * 4;
unsigned char trailing_char = url ? '.' : '=';
const char* base64_chars_ = base64_chars[url];
std::string ret;
ret.reserve(len_encoded);
unsigned int pos = 0;
while (pos < in_len) {
ret.push_back(base64_chars_[(bytes_to_encode[pos + 0] & 0xfc) >> 2]);
if (pos+1 < in_len) {
ret.push_back(base64_chars_[((bytes_to_encode[pos + 0] & 0x03) << 4) + ((bytes_to_encode[pos + 1] & 0xf0) >> 4)]);
if (pos+2 < in_len) {
ret.push_back(base64_chars_[((bytes_to_encode[pos + 1] & 0x0f) << 2) + ((bytes_to_encode[pos + 2] & 0xc0) >> 6)]);
ret.push_back(base64_chars_[ bytes_to_encode[pos + 2] & 0x3f]);
}
else {
ret.push_back(base64_chars_[(bytes_to_encode[pos + 1] & 0x0f) << 2]);
ret.push_back(trailing_char);
}
}
else {
ret.push_back(base64_chars_[(bytes_to_encode[pos + 0] & 0x03) << 4]);
ret.push_back(trailing_char);
ret.push_back(trailing_char);
}
pos += 3;
}
return ret;
}
图片编码测试:
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char const *argv[])
{
ifstream in("100.jpg", ifstream::binary);
istreambuf_iterator<char> beg(in), end;
string content;
content.assign(beg,end);
in.close();
std::string encoded = base64_encode(reinterpret_cast<const unsigned char*>(content.data()), content.length());
cout << encoded << endl;
return 0;
}
注意,编码出来的数据是没有base64头的,要在浏览器显示需要自己加上data:image/jpg;base64,
。
然后用<img id="snap_pic" width="300", height="200", src="https://img-blog.csdnimg.cn/2022010707451887696.jpg"/>
即可显示。