- 直接展示
import io
from flask import Response
import matplotlib as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
from flask import Flask
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
app = Flask(__name__)
@app.route('/print-plot')
def plot_png():
fig = Figure()
axis = fig.add_subplot(1, 1, 1)
xs = np.random.rand(100)
ys = np.random.rand(100)
axis.plot(xs, ys)
output = io.BytesIO() # 数据读写不一定是文件,也可以在内存中读写
FigureCanvas(fig).print_png(output)
return Response(output.getvalue(), mimetype='image/png')
app.run(debug = True)
- 直接展示【保存图片到内存】
# python -m pip install -U scikit-image
import io
from flask import Flask, send_file
import numpy as np
from skimage.io import imsave
import matplotlib.pyplot as plt
app = Flask(__name__)
app.debug = True
@app.route('/')
def generate_image():
"""
Return a generated image as a png by
saving it into a StringIO and using send_file.
"""
num_tiles = 20
tile_size = 30
arr = np.random.randint(0, 255, (num_tiles, num_tiles, 3))
arr = arr.repeat(tile_size, axis=0).repeat(tile_size, axis=1)
# We make sure to use the PIL plugin here because not all skimage.io plugins
# support writing to a file object.
strIO = io.BytesIO()
imsave(strIO, arr, plugin='pil', format_str='png')
strIO.seek(0)
return send_file(strIO, mimetype='image/png')
@app.route('/plot')
def generate_plot():
"""
Return a matplotlib plot as a png by
saving it into a StringIO and using send_file.
"""
def using_matplotlib():
fig = plt.figure(figsize=(6, 6), dpi=300)
ax = fig.add_subplot(111)
x = np.random.randn(500)
y = np.random.randn(500)
ax.plot(x, y, '.', color='r', markersize=10, alpha=0.2)
ax.set_title('Behold')
strIO = io.BytesIO()
plt.savefig(strIO, dpi=fig.dpi)
strIO.seek(0)
return strIO
strIO = using_matplotlib()
return send_file(strIO, mimetype='image/png')
if __name__ == '__main__':
app.run()
- 保存图片显示(文件)
# https://stackoverflow.com/questions/50728328/python-how-to-show-matplotlib-in-flask
In order to serve images in flask by HTML, you will need to store the image in your flask file directory:
static/
images/
plot.png --> store plots here
templates/
Therefore, in your application, use plt.savefig:
import io
import random
from flask import Response
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
@app.route('/test')
def chartTest():
lnprice=np.log(price)
plt.plot(lnprice)
plt.savefig('/static/images/new_plot.png')
return render_template('untitled1.html', name = 'new_plot', url ='/static/images/new_plot.png')
Then in untitled1.html:
<p>{{ name }}</p>
<img src={{ url}} alt="Chart" height="42" width="42">
<!doctype html>
<html>
<body>
<h1>Price Chart</h1>
<p>{{ name }}</p>
<img src={{ name }} alt="Chart" height="42" width="42">
</body>
</html>