Jun-10-2021, 06:58 PM
Hello,
I have a matplotlib figure that I want to return as a base64Encoded variable so it can be stored as a blob object. This variable would be the return result of a REST service so saving it directly to disk does not fit the project requirements.
I've tried various methods, but I cannot quite get the base64Encoded approach to work.
After the matplotlib is done, the following does create a disk file correctly:
---
I also tried to just write the data from the above directly to disk without an intermediate program:
Would appreciate some suggestions.
Thanks!
Oliver
I have a matplotlib figure that I want to return as a base64Encoded variable so it can be stored as a blob object. This variable would be the return result of a REST service so saving it directly to disk does not fit the project requirements.
I've tried various methods, but I cannot quite get the base64Encoded approach to work.
After the matplotlib is done, the following does create a disk file correctly:
[b]plt.savefig[/b]('test_file_spectrogram.png')Now, to return that same figure as a base64Encoded variable, I tried this:
my_stringIObytes = io.BytesIO() plt.savefig(my_stringIObytes, format='png') my_stringIObytes.seek(0) my_base64_jpgData = base64.b64encode(my_stringIObytes.read())But when I convert this back to base64.decode(), it does not display a file. In fact, the actual png above is about 100KB, but this version when converted back is only 4KB.
---
I also tried to just write the data from the above directly to disk without an intermediate program:
with open('base64_decode_test.png', 'wb') as fl: fl.write(my_stringIObytes.getbuffer()) fl.close()But that doesn't work correctly either.
Would appreciate some suggestions.
Thanks!
Oliver