【问题标题】:I am trying to pass an image from python to html but I am having difficulty opening the image我正在尝试将图像从 python 传递到 html,但我无法打开图像
【发布时间】:2021-04-09 16:34:04
【问题描述】:

此方法需要接收图形类型、要工作的文件和要绘制的坐标轴

@app.route('/graficar',methods=['POST'])
def graficar():
    if request.method == 'POST':
         
        tipo=request.form['tipo']
        nombre=request.form['nombre']
        sep=request.form['sep']
        columnaX=request.form['columnaX']        
        columnaY=request.form['columnaY']
        ruta=request.form['fil']
        df =pd.read_csv(ruta, sep=sep )
        df=df.head(10)
        print(df.head(5))
        if tipo=='1':
            print('Lineal')
            plt.plot(df[columnaX],df[columnaY])
            plt.xticks(df[columnaX], rotation=75)
            plt.xlabel(columnaX)
            plt.ylabel(columnaY)
            plt.title(nombre)
            plt.show()
            plt.savefig('img/Grafica.png' )
            return render_template("Grafica.html")

HTML,我只是发送调用图像,但它没有显示任何内容
enter image description here

<div class="col-12">
      <h3 class="text-center display-2">Gráfica</h3>
      <div class="container ">
           <img class="img-fluid" src="img/Grafica.png" alt="Chania" />
      </div>
 </div>


  

【问题讨论】:

  • 请添加您的环境的文件夹映射,您的代码的默认文件夹和您存储图像的文件夹之间的关系,通常有一个static 文件夹,您可以在其中存储您的数据发布,因此编程中使用的路径与 HTML 文件中的路径不同。

标签: python html pandas matplotlib flask


【解决方案1】:

我的建议是不要将文件保存在某处,而是即时创建图像。创建一个将提供渲染图像的端点,以及一个将呈现您的页面模板的端点。将它们分开将使一切变得更快、更容易调试和更具可读性。

查看此答案以了解如何从 Flask 端点返回图像。 Python: How to show matplotlib in flask

作为一个简单的例子来说明它是如何工作的:

main.py:

import io
import random

from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from flask import Flask, Response, render_template, request

# Create the app
app = Flask(__name__)


def create_figure(title: str = "", **kwargs) -> Figure:

    # Create a plot here...
    figure = Figure()
    axis = figure.add_subplot(title=title)
    xs = range(100)
    ys = [random.randint(1, 50) for _ in xs]
    axis.plot(xs, ys)
    return figure


@app.route("/img/Grafica.png")
def get_image():

    # Get the input arguments (e.g. /img/Grafica.png?title=test)
    # You can also use request.form here
    args = dict(request.args)

    # Create the figure or whatever you need to plot
    figure = create_figure(**args)

    # Create a buffer to hold the PNG
    buffer = io.BytesIO()

    # Write the figure as PNG to the buffer
    FigureCanvas(figure).print_png(buffer)

    # Return the binary contents of the buffer, set the mimetype to indicate to the browser that we've send an image
    return Response(buffer.getvalue(), mimetype="image/png")


@app.route("/graficar")
def get_graficar():
    return render_template("Grafica.html")


if __name__ == "__main__":
    app.run(debug=True)

templates/Grafica.html:

<!doctype html>

<section class="content">
  <h1>Graficar</h1>
  <img src="/img/Grafica.png?title=My title" />
</section>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多