0

I sending image encoded in Base64 on my c++ server as json value and trying to decode it back and save on disk as .jpg file. And i have a problem with decoding, its saves on disk but not opening, size of the input and output file slighly different (40.8 kb vs 41.1 kb). I tryed 3 different decoding code, this is the last one:

typedef unsigned char uchar;
static const std::string b = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";//=
std::string PictureManager::base64_decode(const std::string& in) {
    std::string out;

    std::vector<int> T(256, -1);
    for (int i = 0; i < 64; i++) T[b[i]] = i;

    int val = 0, valb = -8;
    for (uchar c : in) {
        if (T[c] == -1) break;
        val = (val << 6) + T[c];
        valb += 6;
        if (valb >= 0) {
            out.push_back(char((val >> valb) & 0xFF));
            valb -= 8;
        }
    }
    return out;
}

And this is my saving function :

  bool PictureManager::SavePicture(std::string DecodedString)
{
    std::ofstream Picture;
    Picture.open("PicturePatch.jpg");
    if (!Picture.is_open())
    {
        std::cout << "Error in opening file!" << std::endl;
        return false;
    }
    /*for(std::vector<BYTE>::iterator it = DecodedString.begin(); it != DecodedString.end(); it++)
    {
        Picture << *it;
    
    }*/
    
    Picture << DecodedString;

    return true;
}

Please help

special
  • 11
  • 7
  • 1
    You forgot to open the file as binary. Also see the use of the `write` method: [Writing binary data to fstream in c++](https://stackoverflow.com/questions/49492259/writing-binary-data-to-fstream-in-c) – Botje Nov 19 '20 at 09:57
  • You open the picture file as text, not as binary. It might be the problem, you gave the decode method, which worked for me, while the problem might be in encode, or image read (also as text instead of binary?). – SHR Nov 19 '20 at 10:03
  • @Botje I just use binary mode with this "std::ios::app | std::ios::binary" and it works, thank you very much mate! another time!) – special Nov 19 '20 at 10:07
  • Just the binary flag, I don't think you want to append to an existing file. – Botje Nov 19 '20 at 10:08
  • @SHR Yeah, its exactly what i need, open with binary mode, thanks! – special Nov 19 '20 at 10:09

1 Answers1

0

Check things:

Read the file then write it and check: both are the same?

You can compare files using: fc /b f1.jpg f2.jpg

Then check both encode and decode. then use memcmp to ensure both are the same.

SHR
  • 7,940
  • 9
  • 38
  • 57