将图像.jpg转换为 Base64

Convert image.jpg to Base64

本文关键字:Base64 转换 jpg 图像      更新时间:2023-10-16

我工作的公司要求我找到一种将图像转换为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

这对

我有用: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();
    }
}