Flask: How to use BytesIO in Flask to display matplotlib image without saving in file.
Example shows how to
- use BytesIO
to create file-like object in memory
- save matplotlib
image in this object in format png
- get data from this object
- convert data to string encoded base64
- create HTML image tag with embede image base64
from flask import Flask
#from flask import render_template
import matplotlib.pyplot as plt
import io
import base64
app = Flask(__name__)
@app.route('/plot')
def build_plot():
img = io.BytesIO()
y = [1,2,3,4,5]
x = [0,2,1,3,4]
plt.plot(x,y)
plt.savefig(img, format='png')
img.seek(0)
plot_url = base64.b64encode(img.getvalue()).decode()
return '<img src="data:image/png;base64,{}">'.format(plot_url)
if __name__ == '__main__':
app.run(debug=True)
You can also save matplotlib
image as jpg
and then you will need jpeg
in src="data:image/jpeg;base64,{}"
.
In similar way you can embed in HTML other files.
If you like it
Buy a Coffee
