This question already has answers here:
How to serve static files in Flask
(24 answers)
Closed 6 days ago.
I'm trying to render an image in html in flask, the path is pointing to the correct file but its not rendering some how.
#VIEWS
#inventory_bp.route("/show")
def show_image():
id = 3
image = Images.query.get(id)
upload_folder = app.config['UPLOAD_FOLDER']
image_path = os.path.join(upload_folder, image.filename)
return render_template("image-upload.html",image_url=image_path)
#HTML
<div>
<img src="{{ image_url }}" alt="" />
</div>
UPLOAD_FOLDER = os.path.join(os.getcwd(), 'flaskbp/uploads')
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
The image_path you're creating is the file path on your OS (e.g. C:\path\to\project\flaskbp\uploads\image.png. This is not the right src for the img element on your HTML.
Instead, you can place the uploads folder under the static folder, and then create the URL of the image dynamically.
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/show")
def show_image():
image_path = "uploads/image.png"
return render_template("image.html", image_url=image_path)
<div>
<img src="{{ url_for('static', filename=image_url) }}"/>
</div>
Folder structure:
\---root
| app.py
|
+---static
| \---uploads
| image.png
|
\---templates
image.html
Related
I want to load an image from the folder do some processing on it and then show it on the HTML page without storing on the disk. I followed this post which discusses similar problem but image is not showing
Here is the code I am using
app.py
from flask import Flask, render_template
from base64 import b64encode
import cv2 as cv
import os
app = Flask(__name__)
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
target = os.path.join(APP_ROOT, 'static')
#app.route("/")
def index():
uri1 = ''
return render_template("output.html", uri1=uri1)
#app.route("/img_prcoess", methods=['POST'])
def img_prcoess():
# Read the image
src_img = cv.imread("/".join([target, 'bradley_cooper.jpg']))
# Convert image to Gray
img1_gray = cv.cvtColor(src_img, cv.COLOR_BGR2GRAY)
# Encode
uri1 = "data:%s;base64,%s" % ("image/jpeg", b64encode(img1_gray))
return render_template("output.html", uri1=uri1)
if __name__ == "__main__":
app.run(port=4444, debug=True)
output.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form id="form1" action="{{ url_for('img_prcoess') }}" method="POST" enctype="multipart/form-data">
<input type="submit" value="Show Image" id="button1" width="100px">
</form>
<img style="height: 300px" src="{{ uri1 }}">
</body>
Directory Structure
You cannot convert the raw data of the image into a data url. You have to change the format first.
#app.route('/process', methods=['POST'])
def process():
path = os.path.join(APP_ROOT, 'static', 'example.jpg')
srcimg = cv.imread(path)
dstimg = cv.cvtColor(srcimg, cv.COLOR_BGR2GRAY)
retval, buffer = cv.imencode('.jpg', dstimg)
uri = "data:%s;base64,%s" % ('image/jpeg', b64encode(buffer).decode('ascii'))
return render_template('process.html', **locals())
I am trying to make the webpage in a way that I can access some images, which are saved in the 'static/images' folder, via a hyperlink embedded under their respective names. I tried embedding a link in a page like this but the webpage had a very small icon that didn't show the image.
<!DOCTYPE html>
<html>
<body>
go
</body>
</html>
from flask import Flask, render_template, session, redirect, request, url_for
import pandas as pd
import os
IMG_FOLDER = os.path.join('static', 'images')
app = Flask(__name__)
app.config['IMG_FOLDER'] = IMG_FOLDER
#app.route('/',methods=["GET"])
def homePage():
return render_template("index.html")
#app.route('/')
#app.route('/goto/<name>')
def show_index(name):
file = name
full_filename = os.path.join(app.config['IMG_FOLDER'], file)
return render_template("goto.html", user_image = full_filename)
if __name__ == "__main__":
app.run(debug=True)
<!DOCTYPE html>
<html>
<body>
<img src="{{ user_image }}" alt="User Image">
</body>
</html>
On the contrary, when I am using this in the following way it shows up fine -
from flask import Flask, render_template, session, redirect, request, url_for
import pandas as pd
import os
IMG_FOLDER = os.path.join('static', 'images')
app = Flask(__name__)
app.config['IMG_FOLDER'] = IMG_FOLDER
#app.route('/',methods=["GET"])
def homePage():
return "hello"
#app.route('/')
#app.route('/goto')
def show_index():
file = 'Koala.png'
full_filename = os.path.join(app.config['IMG_FOLDER'], file)
return render_template("goto.html", user_image = full_filename)
if __name__ == "__main__":
app.run(debug=True)
I may be doing something wrong somewhere. Any help would be much appreciated. I am trying to embed these names in the form of for loop in a data-frame. Anyway, thanks in advance!
full_filename = os.path.join(app.config['IMG_FOLDER'], file) will return static\images\file. However, what you need is: \static\images\file. Therefore, what you need to run is:
full_filename = "\\" + os.path.join(app.config['IMG_FOLDER'], file).
Alternatively, if you want to display the image and have a link to goto, you could do the following:
<!DOCTYPE html>
<html>
<body>
<a href="/goto/{{user_image.split('\\')[3]}}">
<img src="{{user_image}}" alt="User Image">
</a>
</body>
</html>
I am very new to python and Flask.
I have a folder with a list of jpeg images. I have to display them in my demo application with flask as below,
My app.py :
#app.route("/")
def home():
return render_template('home.html')
My home.html:
<img id="person" src={{ url_for('static',filename='pferson_folder/000_1.jpg') }}>
In the above code, I don't want to hardcode the images in the HTML tag. it needs to take the image source from folder dynamically.
Would you please help me with this. Thank you.
You can read all the file names out of the directory using os.listdir('Your path') and pass the array into the template:
Something like:
# Inside app.py
import os
#app.route('/')
def home():
image_names = os.listdir('Your path to images folder')
render_template('home.html', image_name=image_names)
And inside your template:
{% for name in image_names %}
<img src="{{ url_for('static', filename='pferson_folder/' + name) }}" >
{% endfor %}
Then you don't have to hardcode the names.
This question already has answers here:
How to serve static files in Flask
(24 answers)
Link to Flask static files with url_for
(2 answers)
Closed 5 years ago.
I am trying to pass a filename of an image and render it on a template,
Although I am passing the actual name through it does not display on the page
#app.route('/', methods=['GET','POST'])
#app.route('/start', methods=['GET','POST'])
def start():
person_to_show = 'tim'
profilepic_filename = os.path.join(people_dir, person_to_show, "img.jpg")
return render_template('start.html',profilepic_filename =profilepic_filename )
For example: profilepic_filename = /data/tim/img.jpg
I have tried
{{profilepic_filename}}
<img src="{{ url_for('data', filename='tim/img.jpg') }}"></img>
And I have also tried
<img src="{{profilepic_filename}}"></img>
Neither of which worked
I have created people_photo in static folder and placed an image named shovon.jpg. From the application.py I passed the image as variable to template and showed it using img tag in the template.
In application.py:
from flask import Flask, render_template
import os
PEOPLE_FOLDER = os.path.join('static', 'people_photo')
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = PEOPLE_FOLDER
#app.route('/')
#app.route('/index')
def show_index():
full_filename = os.path.join(app.config['UPLOAD_FOLDER'], 'shovon.jpg')
return render_template("index.html", user_image = full_filename)
In index.html:
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<img src="{{ user_image }}" alt="User Image">
</body>
</html>
Output:
This question already has answers here:
Refering to a directory in a Flask app doesn't work unless the path is absolute
(1 answer)
Saving upload in Flask only saves to project root
(1 answer)
Flask: IOError when saving uploaded files
(2 answers)
Closed 4 years ago.
I've looked at a couple of the other questions but can't figure out what is going wrong. I get the following error: "FileNotFoundError: [Errno 2] No such file or directory: '/uploads\MRRtest.csv'" Can anyone help? What is the difference between the forward and backward slashes on the error message?
Thanks
from flask import Flask, render_template, request, redirect, url_for, flash
from flask.ext.bootstrap import Bootstrap
from werkzeug import secure_filename
import os
app = Flask(__name__)
bootstrap = Bootstrap(app)
UPLOAD_FOLDER = '/uploads'
ALLOWED_EXTENSIONS = set(['csv'])
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
#app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'],filename))
return redirect(url_for('uploaded_file', filename=filename))
return render_template('index.html')
My index.html template is as follows:
{% extends "base.html" %}
{% block title %}Flasky{% endblock %}
{% block page_content %}
<div class="page-header">
<h1>Upload File</h1>
<form action="" method=post enctype=multipart/form-data>
<p><input type=file name=file>
<input type=submit value=Upload>
</form>
</div>
{% endblock %}
/uploads means an absolute link (C:/upload), so you should use upload/ instead.
Also, you can use the nice snippet from https://stackoverflow.com/a/20257725/5851179
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
UPLOAD_FOLDER = os.path.join(APP_ROOT, 'static/uploads')
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
Just realized from the comments that my uploads directory is in the same directory as my run.py file rather than the 'templates' directory that index.html is running from. I modified the
UPLOAD_FOLDER = '/uploads'
to
UPLOAD_FOLDER = './uploads'
I'll now work on building the "url for endpoint"
Thanks for your help.