简体   繁体   中英

Convert image.jpg to Base64

The company I'm working for has asked me to find a way to convert an image into 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.

I will then have to do :

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

In Javascript and do the Jquery.

I've tried using the ifstream with ios::in | ios::binary and just reading the file and outputting the result but it doesn't work.

#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

I can't believe C++ doesn't have base64 functionality in the standard library!

#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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM