I need to save a Matplot plot to a temporary file that I control since this code would be in a python Flask REST service.
I tried this:
fp = tempfile.NamedTemporaryFile() return_base64 = ""
with fp:
fp.write(plt.savefig) # THIS IS WRONG....
with open(fp.name, 'rb') as open_it:
open_it.seek(0)
return_base64 = str(base64.b64encode(open_it.read()))
# strip off leading b and ' and trailing '
return_base64 = return_base64[2: len(return_base64) - 1]
open_it.close()
fp.close()
But, "fp.write" doesn't work with saving the plt.savefig as I did above.
My issue is that I'm using the PRAAT phonetic library and there does not seem to be a way to use the "Sound()" method inside a REST service. Thus, I'm doing lots of temporary files to work around this.
So, how do I write the matplotib plot to a named temporary file?
Appreciation and thanks in advance.
i am sharing this code it is storing jpg file in my temporary folder
import io
buf = io.BytesIO()
plt.savefig(buf, format="jpg")
#print(buf.getvalue()) return bytes of plot
fp = tempfile.NamedTemporaryFile()
# print(fp.name) return file name
with open(f"{fp.name}.jpg",'wb') as ff:
ff.write(buf.getvalue())
buf.close()