C++ Base64

網(wǎng)上找的趾浅,忘了原地址

#include <stdint.h>
#include <chrono>
#include <string>
#include <stdio.h>
using namespace std;

static const char* encode_chars[2] = {
             "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
             "abcdefghijklmnopqrstuvwxyz"
             "0123456789"
             "+/",
             "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
             "abcdefghijklmnopqrstuvwxyz"
             "0123456789"
             "-_"};
// Avoiding name mangling
extern "C" {
//轉(zhuǎn)碼base64
   __attribute__((visibility("default"))) __attribute__((used))
  const char* encode_base64(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 ? '.' : '=';
 //
 // Choose set of base64 characters. They differ
 // for the last two positions, depending on the url
 // parameter.
 // A bool (as is the parameter url) is guaranteed
 // to evaluate to either 0 or 1 in C++ therefore,
 // the correct character set is chosen by subscripting
 // base64_chars with url.
 //
       const char* base64_chars_s = encode_chars[url];
       std::string ret;
       ret.reserve(len_encoded);
       unsigned int pos = 0;
       while (pos < in_len) {
          ret.push_back(base64_chars_s[(bytes_to_encode[pos + 0] & 0xfc) >> 2]);
          if (pos+1 < in_len) {
             ret.push_back(base64_chars_s[((bytes_to_encode[pos + 0] & 0x03) << 4) + ((bytes_to_encode[pos + 1] & 0xf0) >> 4)]);
             if (pos+2 < in_len) {
                ret.push_back(base64_chars_s[((bytes_to_encode[pos + 1] & 0x0f) << 2) + ((bytes_to_encode[pos + 2] & 0xc0) >> 6)]);
                ret.push_back(base64_chars_s[  bytes_to_encode[pos + 2] & 0x3f]);
             }
             else {
                ret.push_back(base64_chars_s[(bytes_to_encode[pos + 1] & 0x0f) << 2]);
                ret.push_back(trailing_char);
             }
          }
          else {
              ret.push_back(base64_chars_s[(bytes_to_encode[pos + 0] & 0x03) << 4]);
              ret.push_back(trailing_char);
              ret.push_back(trailing_char);
          }
          pos += 3;
    }
    const char *p = ret.c_str();
    return p;
}
static unsigned int pos_of_char(const unsigned char chr) {
 //
 // Return the position of chr within base64_encode()
 //
    if      (chr >= 'A' && chr <= 'Z') return chr - 'A';
    else if (chr >= 'a' && chr <= 'z') return chr - 'a' + ('Z' - 'A')               + 1;
    else if (chr >= '0' && chr <= '9') return chr - '0' + ('Z' - 'A') + ('z' - 'a') + 2;
    else if (chr == '+' || chr == '-') return 62; // Be liberal with input and accept both url ('-') and non-url ('+') base 64 characters (
    else if (chr == '/' || chr == '_') return 63; // Ditto for '/' and '_'
    else
 //
 // 2020-10-23: Throw std::exception rather than const char*
 //(Pablo Martin-Gomez, https://github.com/Bouska)
 //
    throw std::runtime_error("Input is not valid base64-encoded data.");
}
static std::string decode_base64(String encoded_string) {
    if (encoded_string.empty()) return std::string();
    size_t length_of_string = encoded_string.length();
    size_t pos = 0;
 //
 // The approximate length (bytes) of the decoded string might be one or
 // two bytes smaller, depending on the amount of trailing equal signs
 // in the encoded string. This approximation is needed to reserve
 // enough space in the string to be returned.
 //
    size_t approx_length_of_decoded_string = length_of_string / 4 * 3;
    std::string ret;
    ret.reserve(approx_length_of_decoded_string);
    while (pos < length_of_string) {
    //
    // Iterate over encoded input string in chunks. The size of all
    // chunks except the last one is 4 bytes.
    //
    // The last chunk might be padded with equal signs or dots
    // in order to make it 4 bytes in size as well, but this
    // is not required as per RFC 2045.
    //
    // All chunks except the last one produce three output bytes.
    //
    // The last chunk produces at least one and up to three bytes.
    //
       size_t pos_of_char_1 = pos_of_char(encoded_string[pos+1] );
    //
    // Emit the first output byte that is produced in each chunk:
    //
       ret.push_back(static_cast<std::string::value_type>( ( (pos_of_char(encoded_string[pos+0]) ) << 2 ) + ( (pos_of_char_1 & 0x30 ) >> 4)));
       if ( ( pos + 2 < length_of_string  )       &&  // Check for data that is not padded with equal signs (which is allowed by RFC 2045)
              encoded_string[pos+2] != '='        &&
              encoded_string[pos+2] != '.'            // accept URL-safe base 64 strings, too, so check for '.' also.
          )
       {
       //
       // Emit a chunk's second byte (which might not be produced in the last chunk).
       //
          unsigned int pos_of_char_2 = pos_of_char(encoded_string[pos+2] );
          ret.push_back(static_cast<std::string::value_type>( (( pos_of_char_1 & 0x0f) << 4) + (( pos_of_char_2 & 0x3c) >> 2)));
          if ( ( pos + 3 < length_of_string )     &&
                 encoded_string[pos+3] != '='     &&
                 encoded_string[pos+3] != '.'
             )
          {
          //
          // Emit a chunk's third byte (which might not be produced in the last chunk).
          //
             ret.push_back(static_cast<std::string::value_type>( ( (pos_of_char_2 & 0x03 ) << 6 ) + pos_of_char(encoded_string[pos+3])   ));
          }
       }
       pos += 4;
    }
    return ret;
}

調(diào)用

    void baseStr2Mat(char *base64Str){
        std::string str = base64Str;
        string decoded_string = decode_base64(str);
        vector<uchar> data(decoded_string.begin(), decoded_string.end());
       //..拿到data去轉(zhuǎn)換 如: Mat mat = imdecode(data, IMREAD_UNCHANGED);
    }
  
   const char* mat2BaseStr(char* imagePath){
         Mat srcMat;
         srcImage = imread(inputImagePath,IMREAD_UNCHANGED);
         std::vector<uchar> buf;
        //圖片轉(zhuǎn)成buf 如:cv::imencode(".jpg", srcMat, buf);
         auto *msg = reinterpret_cast<unsigned char*>(buf.data());
        const char* p = encode_base64(msg, buf.size(),false);
        return p;
      }

flutter讀取base64圖片

Image.memory(
           base64Decode(base64Str),
           //防止重繪
           gaplessPlayback: true,
           width: 100,
           height: 100,
           fit: BoxFit.cover,
         ),
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市馒稍,隨后出現(xiàn)的幾起案子皿哨,更是在濱河造成了極大的恐慌,老刑警劉巖纽谒,帶你破解...
    沈念sama閱讀 219,188評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件证膨,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡鼓黔,警方通過查閱死者的電腦和手機(jī)央勒,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,464評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來澳化,“玉大人崔步,你說我怎么就攤上這事∷敛叮” “怎么了刷晋?”我有些...
    開封第一講書人閱讀 165,562評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)慎陵。 經(jīng)常有香客問我眼虱,道長(zhǎng),這世上最難降的妖魔是什么席纽? 我笑而不...
    開封第一講書人閱讀 58,893評(píng)論 1 295
  • 正文 為了忘掉前任捏悬,我火速辦了婚禮,結(jié)果婚禮上润梯,老公的妹妹穿的比我還像新娘过牙。我一直安慰自己,他們只是感情好纺铭,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,917評(píng)論 6 392
  • 文/花漫 我一把揭開白布寇钉。 她就那樣靜靜地躺著,像睡著了一般舶赔。 火紅的嫁衣襯著肌膚如雪扫倡。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,708評(píng)論 1 305
  • 那天竟纳,我揣著相機(jī)與錄音撵溃,去河邊找鬼疚鲤。 笑死,一個(gè)胖子當(dāng)著我的面吹牛缘挑,可吹牛的內(nèi)容都是我干的集歇。 我是一名探鬼主播,決...
    沈念sama閱讀 40,430評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼语淘,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼诲宇!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起亏娜,我...
    開封第一講書人閱讀 39,342評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤焕窝,失蹤者是張志新(化名)和其女友劉穎蹬挺,沒想到半個(gè)月后维贺,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,801評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡巴帮,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,976評(píng)論 3 337
  • 正文 我和宋清朗相戀三年溯泣,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片榕茧。...
    茶點(diǎn)故事閱讀 40,115評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡垃沦,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出用押,到底是詐尸還是另有隱情肢簿,我是刑警寧澤,帶...
    沈念sama閱讀 35,804評(píng)論 5 346
  • 正文 年R本政府宣布蜻拨,位于F島的核電站池充,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏缎讼。R本人自食惡果不足惜收夸,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,458評(píng)論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望血崭。 院中可真熱鬧卧惜,春花似錦、人聲如沸夹纫。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,008評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽舰讹。三九已至茅姜,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間跺涤,已是汗流浹背匈睁。 一陣腳步聲響...
    開封第一講書人閱讀 33,135評(píng)論 1 272
  • 我被黑心中介騙來泰國(guó)打工监透, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,365評(píng)論 3 373
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像眷篇,于是被迫代替她去往敵國(guó)和親又跛。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,055評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容