[英]Convert image.jpg to Base64
The company I'm working for has asked me to find a way to convert an image into Base64. 我正在工作的公司要求我找到一种将映像转换为Base64的方法。 Basically, there is a camera that will be taking pictures in JPG and I need to convert that JPG picture in Base64 so that I can send the data through a PLC program and rebuild it on the application side which is going to be a web app.
基本上,有一台照相机将以JPG格式拍摄照片,我需要在Base64中转换该JPG图片,以便我可以通过PLC程序发送数据并在将要成为Web应用程序的应用程序端重建它。
I will then have to do : 然后,我将不得不做:
document.getElementById("ImageLoad").src = "data:image/png;base64," + Bytes;
In Javascript and do the Jquery. 用Javascript做Jquery。
I've tried using the ifstream with ios::in | 我试过使用ifstream与ios :: in | ios::binary and just reading the file and outputting the result but it doesn't work.
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();
}
}
I'm expecting an output like the following: 我期望输出如下所示:
/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAAYEBAQFBA
But I'm getting a long string looking like this: 但是我得到的长字符串如下所示:
}!× ÙÝÜ÷åXŠmŒš@Õä ‡6gxD1;*wïµ¼4 ÒÑôÿ ¿OÑú\\x0¥ˆ'ÀÃõûóC
This worked for me: https://renenyffenegger.ch/notes/development/Base64/Encoding-and-decoding-base-64-with-cpp 这对我有用 : https : //renenyffenegger.ch/notes/development/Base64/Encoding-and-decoding-base-64-with-cpp
I can't believe C++ doesn't have base64 functionality in the standard library! 我不敢相信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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.