I am trying to convert the Base-64 data contained in the “data” returned by toDataURL of a fabric.Canvas into a file with its corresponding extension (BMP). The result is a “The file is not in the correct format” error.
The steps I follow are the following.
-
I get the dataURL variable from the fabric.Canvas with the toDataURL method.
dataURL = canvas.toDataURL({
format: ‘bmp’,
quality: 1.0
});
-
I extract only the string that contains the “data”.
dataURLto64 = dataURL.substr(dataURL.lastIndexOf(‘,’) + 1, dataURL.length –
dataURL.lastIndexOf(‘,’) – 1); -
The above is done on the client. On the server I needed to save the string in segments in a TXT text file. I have verified that the final content of the text file is identical to the original dataURLto64 (in Base-64).
-
I extract the content of the text file.
string strtextfile64 = File.ReadAllText([path]);
-
I convert that string into a byte array with the method
byte[] fileBinary = null;
fileBinary = Convert.FromBase64String(strtextfile64);
File.WriteAllBytes([path], fileBinary);
I have verified that both, dataURLto64 and strtextfile64 have the same characters and the same number.
To verify that the Base-64 string is correct, I have included the following verification on the server.
int mod4 = strtextfile64.Length % 4;
if (mod4 > 0) {
strtextfile64 += new string('=', 4 - mod4);
}
It was not necessary to modify strtextfile64 because mod4 = 0.
I am attaching two text files in which the initial (client) and final (server) Base-64 strings are contained.
Inicial cliente
Final servidor
Could someone tell me the reason why that Base-64 data converted to binary data does not comply with the original BMP format from the original BMP file created from the fabric.Canvas?