I am trying to pass an image from python to html but I am having difficulty opening the image

Issue

This Method receives type of Graph is required, the file to work and the axes to graph

@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,I just send to call the image but it does not show me anything
enter image description here 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>


  

Solution

My suggestion would be to not save the file somewhere, but create the image on the fly. Create an endpoint that will serve the rendered image, and an endpoint that will render your page template. Separating these will make everything faster, easier to debug and more readable.

Have a look at this answer to get an idea of how to return an image from a Flask endpoint.
Python: How to show matplotlib in flask

As a quick example of how it would work:

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>

Output

Answered By – Gijs Wobben

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published