I have a code that retrieves an Base64 String from an API call. Since the image can be bigger than the allowed variable storage size, I store the String in a .txt file.
After cleaning this file I start the process of decoding the Base64 and transforming it into a BMP image file. Unfortunally, the result is not what is to be expected. I'm able to open the file, meaning it's not corrupted/doesn't have errors, but some lines are just plain incorrect with pixels in the wrong positions.
Here is the Base64 String stored on my .txt file: https://nopaste.net/zXJROd2pLy
Here is my code:
#include "base64.hpp" //densaugeo base64 repository
void makeFiguraFromTxt(String fname){
limpaBase64(imgTemp); //Other function of mine that just cleans the .txt file
File file = SD.open(imgTemp, FILE_READ); //File with Base64 String
File bmpFile = SD.open(fname, FILE_WRITE); //File where BMP image will be stored
uint32_t largura; //width
//Header -----------------------------------------------------------------
uint8_t buffer_header[54]; //bmp has the first 54 bytes as header
if (file.available()) {
size_t bytesRead = file.read(buffer_header, sizeof(buffer_header));
String chunk = String((char*)buffer_header);
unsigned int decoded_length = decode_base64_length((unsigned char *)chunk.c_str(), chunk.length());
unsigned char decoded_data[decoded_length];
decode_base64((unsigned char *)chunk.c_str(), decoded_length, decoded_data);
bmpFile.write((uint8_t*)decoded_data, decoded_length);
largura = decoded_data[18] | (decoded_data[19] << 8) | (decoded_data[20] << 16) | (decoded_data[21] << 24);
}
//Stride (amount of bytes per line)
unsigned int stride = ceil((largura * 1)/32)*4;
uint8_t buffer[stride];
while (file.available()){
int bytesRead = file.read(buffer, sizeof(buffer));
String chunk = String((char*)buffer);
Serial.print(chunk);
unsigned int decodedLength = decode_base64_length((unsigned char *)chunk.c_str(), chunk.length());
unsigned char *decodedData = (unsigned char *)malloc(decodedLength);
decode_base64((unsigned char *)chunk.c_str(), decodedLength, decodedData);
bmpFile.write((uint8_t *)decodedData, decodedLength);
free(decodedData);
}
bmpFile.flush();
bmpFile.close();
file.close();
}
I'm not sure why this is happening, so I would like some insight if possible. My suspicion initially was that the lines need to be multiple of 4, but the stride was supposed to solve it.
