Boost 图片/文件转base64编码

Boost 图片/文件转base64编码


1. Boost的Base64

Boost实现了base64的编码,包含在头文件:

#include "boost/archive/iterators/binary_from_base64.hpp"
#include "boost/archive/iterators/base64_from_binary.hpp"
#include "boost/archive/iterators/transform_width.hpp"

网上大多是针对字符串的使用,本示例将对文件或图片的使用提供一个完整的例子。
其中文件的读写使用的C函数,也可以换成C++的stream。

2. 实例

#include <cstdio>
#include <list>
#include <vector>
#include "boost/archive/iterators/binary_from_base64.hpp"
#include "boost/archive/iterators/base64_from_binary.hpp"
#include "boost/archive/iterators/transform_width.hpp"
#include <boost/algorithm/string.hpp>

using namespace boost::archive::iterators;

int main()
{
    //data from file
    FILE* file_in = fopen("/home/ubuntu/Pictures/mars.png","rb");
    if(file_in == NULL)
        return -1;
    fseek (file_in, 0, SEEK_END);
    long size=ftell (file_in);
    char* buffer = (char*)malloc(sizeof(char)*size);
    fseek (file_in, 0, SEEK_SET);
    size_t ret = fread(buffer, sizeof(char), size, file_in);
    fclose (file_in);

    //encode
    typedef 
        base64_from_binary< 
                transform_width<char *, 6, sizeof(char) * 8> 
        >
        base64_encode_itor;

    std::string text_base64; 
    std::copy(
        base64_encode_itor(buffer),
        base64_encode_itor(buffer + size),
        std::back_inserter(text_base64)
    );
    free(buffer);
	//编码填充=
	text_base64.append((3 - size % 3) % 3, '=');
	
    //decode
    //解码前去除最后填充的=
    boost::trim_right_if(text_base64,boost::is_any_of("="));
    typedef	
        transform_width< 
            binary_from_base64< typename std::list<char>::iterator>,
            sizeof(char) * 8, 
            6
        > 
        base64_decode_itor;
    
    std::vector<char> decode_result;
    std::copy(
        base64_decode_itor(text_base64.begin()),
        base64_decode_itor(text_base64.end()), 
        std::back_inserter(decode_result)
    );
    
    //data to file
    FILE* file_out = fopen("/home/ubuntu/Pictures/mars_1.png","wb");
    if(file_out == NULL)
        return -1;
    fwrite(&decode_result[0], sizeof(char), decode_result.size(),file_out);
    fclose(file_out);

    return 0;
}

3. 总结

Boost 的 base64编码总体来说比较繁琐,完整的文档很少,导致使用体验并不好。
我们可以选择其它的base64编码,例如百度云SDK的base64,或者coreutils的base64等,对于基础扎实的人可以直接写编解码函数,并不困难。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值