1

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

Botje
  • 26,269
  • 3
  • 31
  • 41
  • 1
    You need to convert the binary data to base64, see this answer: https://stackoverflow.com/questions/342409/how-do-i-base64-encode-decode-in-c – Frank Buss Jul 09 '19 at 14:46
  • 1
    There are many base64 implementations floating around. Or you could simply write your own, as base64 is very easy to implement manually, it only takes a small handful of lines of code. – Remy Lebeau Jul 09 '19 at 18:08

1 Answers1

1

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();
    }
}
Pseudonymous
  • 839
  • 5
  • 13