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

5
  • 1
    You forgot to open the file as binary. Also see the use of the write method: Writing binary data to fstream in c++ Commented Nov 19, 2020 at 9: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?). Commented Nov 19, 2020 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!) Commented Nov 19, 2020 at 10:07
  • Just the binary flag, I don't think you want to append to an existing file. Commented Nov 19, 2020 at 10:08
  • @SHR Yeah, its exactly what i need, open with binary mode, thanks! Commented Nov 19, 2020 at 10:09

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.