参考:
- C++代码一次读取文本文件全部内容到string对象
- base64和base64URL
- cpp-base64 github
由于只需要编码算法,所及将cpp-base64库中的编码函数单独拿出来,代码如下:
#include// 声明 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#include using namespace std; int main(int argc, char const *argv[]) { ifstream in("100.jpg", ifstream::binary); istreambuf_iterator beg(in), end; string content; content.assign(beg,end); in.close(); std::string encoded = base64_encode(reinterpret_cast (content.data()), content.length()); cout << encoded << endl; return 0; }
注意,编码出来的数据是没有base64头的,要在浏览器显示需要自己加上data:image/jpg;base64,。
然后用即可显示。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)