将image.jpg转换为Base64

时间:2019-07-09 14:40:07

标签: c++ base64

我正在工作的公司要求我找到一种将映像转换为Base64的方法。基本上,有一台照相机将以JPG格式拍摄照片,我需要在Base64中转换该JPG图片,以便我可以通过PLC程序发送数据并在将要成为Web应用程序的应用程序端重建它。

然后我将不得不做:

document.getElementById("ImageLoad").src = "data:image/png;base64," + Bytes;

使用Javascript并执行Jquery。

我尝试将ifstream与ios :: in | ios :: binary,仅读取文件并输出结果,但是不起作用。

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    string line;
    ifstream input("test.jpg", ios::in | ios::binary);
    ofstream output("text.txt");
    if (input.is_open()) {
        while (getline(input,line)) {
            output << line;
        }
        input.close();
    }
}

我期望输出如下:

/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAAYEBAQFBA

但是我得到一个长字符串,像这样:

}!× ÙÝÜ÷åXŠmŒš@Õä ‡6gxD1;*wïµ¼4 ÒÑôÿ ¿OÑú\x0¥ˆ‘ÀÃõûóC

1 个答案:

答案 0 :(得分:0)

这对我有用:https://renenyffenegger.ch/notes/development/Base64/Encoding-and-decoding-base-64-with-cpp

我不敢相信C ++在标准库中没有base64功能!

#include <fstream>
#include <string>
#include "base64.h"

using namespace std;

int main()
{
    string line;

    ifstream input("test.jpg", ios::in | ios::binary);

    ofstream output("text.txt");

    if (input.is_open()) {

        while (getline(input, line)) {

            string encoded = base64_encode(reinterpret_cast<const unsigned char*>(line.c_str()), line.length());

            output << encoded;
        }

        input.close();
    }
}
相关问题