I have written bunch of code but it is not rendering the chart inside HTML for some reason. Program however runs and creates an image in Static folder. Can someone tell me how I can pass this "image" in Jinja2 in in HTML in order to view it in HTML?
Flask code:
#app.route('/', methods=['GET', 'POST'])
def index():
image = False
from flask import Flask, render_template, request
if request.method == 'POST':
a = int(request.form['a'])
x = np.linspace(-20, 20, 20)
y = a * x
plt.plot(x,y)
plt.savefig('C:/Users/name/PycharmProjects/qtcalc1/static/image.png')
image = url_for('static', filename = image)
print(image)
plt.show()
return render_template('graphtry.html', image = image)
Note view function code is indented well on my end. I need solution for how to render this image in my HTML file graphtry.html using Jinja2. My current HTML code is as follows:
<img src ="{{image}}" >
When you write
image = url_for('static', filename = image)
the value of image variable in the argument is False (from line 3). You have to pass the actual filename, that is in this example: image.png.
image = url_for('static', filename='image.png')
And also, remove the extra space after src attribute:
<img src="{{image}}" />
Related
I have a system to load image files from html but once I select my file and load it from the front end I need a python api to read that image file I select. How can I connect python to my html?
So, to be specific it would be to load an image file with html and have my python api (I use flask) download it and read it to extract data.enter image description here
The html to load the file would be:
<form action="" method="POST" enctype=multipart/form-data>
<div class="col-md-6">
<input type="file" name="file">
<input class="button button-block button-primary" type="submit" value="Upload">
</div>
</form>
The python API to download and read the file would be:
import os
from flask import Flask, render_template, request
from werkzeug import secure_filename
from PIL import Image
# instance of the Flask object
app = Flask(__name__)
# Carpeta de subida
app.config['UPLOAD_FOLDER'] = './Archivos GTiff'
#app.route("/")
#app.route("imgeo/upload-img.html")
def upload_file():
# render the template "upload-img.html"
return render_template('upload-img.html')
#app.route('imgeo/upload-img.html')
def viewer():
"""Show a map to view the GeoJSON returned from a ImGeo endpoint"""
return render_template('imgeo/upload-img.html')
#app.route("imgeo/upload-img.html", methods=['POST'])
def uploader():
if request.method == 'POST':
# we get the file from the "file" input
f = request.files['archivo']
filename = secure_filename(f.filename)
# Save the file in the directory "tiff files".
f.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
# We return a satisfactory answer
return "<h1>File uploaded successfully</h1>"
if __name__ == '__main__':
# Start the application
app.run(debug=True)
You could try to encode your image in base64 with JavaScript, send the result with a POST request, and then (in Python) decode it. Check out these two threads:
How can I convert an image into Base64 string using JavaScript? (JavaScript)
Convert string in base64 to image and save on filesystem (Python)
Here is a similar question too:
Sending an image from html to python script through CGI
I am using python-docx-template (docxtpl) to generate a .docx file.
With this data:
docente= {
"id":145,
"lugar_de_nacimiento":"Loja",
"fecha_de_nacimiento":"1973-04-14",
"ciudad":"Loja",
"foto_web_low":"https://sica.utpl.edu.ec/media/uploads/docentes/fotos/web/low/1102904313_low.jpg"
}
I have a function where I pass the image docente['foto_web_low'] to the context and the path of the template:
from docxtpl import DocxTemplate, InlineImage
from docx.shared import Mm
def generaraDocumento(request):
response = HttpResponse(content_type='application/msword')
response['Content-Disposition'] = 'attachment; filename="cv.docx"'
doc = DocxTemplate(str(settings.BASE_DIR) + '/cv_api/templates/docx_filename.docx')
imagen = docente['foto_web_low']
context = {'imagen': imagen}
doc.render(context)
doc.save(response)
return response
The template where I have the image that I want to show docx_filename.docx has this:
The template where I have the data that I want to show docx_filename.docx has this:
Image: {{ imagen }}
When the document is generated, I only get the URL address and not the image, in my template it returns this:
Image: https://sica.utpl.edu.ec/media/uploads/docentes/fotos/web/low/1102904313_low.jpg
How can I make the image appear in the document .docx (docxtpl). Thanks in advance.
The image has to be an instance of docxtpl.InlineImage (see docs).
Another important thing is that the image must be present on the disk. docxtpl doesn't support reading images from a url.
Example:
from docxtpl import InlineImage
from docx.shared import Mm
doc = DocxTemplate(str(settings.BASE_DIR) + '/cv_api/templates/docx_filename.docx')
# The image must be already saved on the disk
# reading images from url is not supported
imagen = InlineImage(doc, '/path/to/image/file.jpg', width=Mm(20)) # width is in millimetres
context = {'imagen': imagen}
# ... the rest of the code remains the same ...
Resize the image first, before add it
make it fit to your space
from PIL import Image
img = Image.open("image-path")
newimg = img.resize((250, 250))
newimg.save("tmplogo.png")
then use the new sized image which name tmplogo.png
doc = DocxTemplate("Base.docx")
dic = {"logo": InlineImage(doc, "tmplogo.png")}
doc.render(dic)
doc.save("test.docx")
You're currently linking the variable foto_web_low to the url and not to an actual image. You will need to download the image first, and then attach it. The code below is not tested, but should be in the right direction:
First, dowload the image:
response = requests.get("https://The_URL_of_the_picture.jpg")
file = open("the_image.png", "wb")
file.write(response.content)
file.close()
And then simply add the image to your variable in the context:
docente= {
"id":145,
...
"foto_web_low":"the_image.png",
...
}
I want to make a webpage with Flask which enables me to search images according to some keywords and return two relevant images in the webpage.
And, assume the keyword is 'Steve jobs' and these images that are related to 'Steve jobs' will be scraped by Google Search and stored in a file called 'Steve jobs'.
But I still cannot display images from my file and return a blank page.
hello.py
#app.route("/about",methods=['GET', 'POST'])
def about():
...
DIR = os.path.join(os.getcwd())
DIR = os.path.join(DIR, query.split()[0])
...
def show_index():
for i,(img,Type) in enumerate(ActualImages[:2]):
try:
req = urllib.request.Request(img, headers=header)
raw_img = urllib.request.urlopen(req).read()
cntr = len([i for i in os.listdir(DIR) if image_type in i]) + 1
print(cntr)
if len(Type)==0:
f = open(os.path.join(DIR,image_type + "_"+ str(cntr)+".jpg"),'wb')
else:
f = open(os.path.join(DIR,image_type + "_"+ str(cntr)+"."+Type),'wb')
f.write(raw_img)
f.close()
except Exception as e:
print('>>> Could not load: '+img)
print(e)
return f
return render_template('about.html', f = f)
about.html
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<img src="{{f}}" alt="f">
</body>
</html>
A typical HTML image tag looks like so:
<img src="/path/image.gif" alt="My Image"/>
As you can see, the src attribute contains a URL telling the browser where to find the image. It will go off and download the image from there. It doesn't contain the image itself. Your code appears to be trying to load the image file's content into the HTML, and that won't work.
(Note - it is possible to directly embed images into HTML, but it's pretty unusual, so I won't talk about that.)
Given that, what you need to is to put the images somewhere, and serve and refer to them as per the answer to How do i link to images not in Static folder in flask.
I am trying to render a image from my sqlite3 database, by using this library:
#!/usr/bin/python3
from flask import Flask, render_template, request, send_file
from flask_sqlalchemy import SQLAlchemy
from io import BytesIO
import base64
#app.route('/show/')
def show():
file_data = FileContents.query.filter_by(id=3).first()
image = b64encode(file_data.data)
return render_template('display.html', image = image)
and putting this variable in the html:
<html>
<body>
<img src="data:image;base64,{{image}}"/>
</body>
</html>
But I can't show the image (I am using python3 and google chorme) can someone help to get it?
You can add the extension. Example: <img src="data:image/png;base64,{{ image }}"\>
And decode image to utf-8 return render_template('display.html', image = image.decode('utf8'))
I am right now writing a program which grabs images from the internet and use them to start a server and write the html.
Here is my code:
import json
import requests
import urllib2
import webserver
import bottle
from bottle import run, route, request
#get images
r = requests.get("http://web.sfc.keio.ac.jp/~t14527jz/midterm/imagelist.json")
r.text
imageli = json.loads(r.text)
i = 1
for image in imageli:
if i <= 5:
fname = str(i)+".png"
urllib.urlretrieve(image,fname)
i += 1
#to start a server
#route('/')
#write a HTML, here is where the problem is,
#the content of html is <image src= "1.png"> but the picture is not on the server.
#and I don't know how to do it
def index():
return "<html><head><title>Final exam</title></head><body> <img src=\"1.png\"/>\n <img src=\"2.png\"/>\n <img src=\"3.png\"/>\n<img src=\"4.png\"/>\n<img src=\"5.png\"/>\n</body></html>"
if __name__ == '__main__':
bottle.debug(True)
run(host='localhost', port=8080, reloader=True)
And I am having a problem that the images cannot be shown on the website, the console says images cannot be found.
How can I solve this problem?
The problem here is that you haven't defined a route for serving your static files. You could set the root directory to serve static files by adding this route:
# To serve static png files from root.
#bottle.get('/<filename:re:.*\.png>')
def images(filename):
return bottle.static_file(filename, root='')
But you should really move these to a subdirectory, as in:
import json
import requests
import urllib
import bottle
from bottle import run, route, request
#get images
r = requests.get("http://web.sfc.keio.ac.jp/~t14527jz/midterm/imagelist.json")
r.text
imageli = json.loads(r.text)
i = 1
for image in imageli:
if i <= 5:
fname = "static/{}.png".format(i) # Note update here
urllib.urlretrieve(image, fname)
i += 1
#to start a server
#route('/')
def index():
return "<html><head><title>Final exam</title></head><body> <img src=\"1.png\"/>\n <img src=\"2.png\"/>\n <img src=\"3.png\"/>\n<img src=\"4.png\"/>\n<img src=\"5.png\"/>\n</body></html>"
# To serve static image files from static directory
#bottle.get('/<filename:re:.*\.(jpg|png|gif|ico)>')
def images(filename):
return bottle.static_file(filename, root='static')
if __name__ == '__main__':
bottle.debug(True)
run(host='localhost', port=8080, reloader=True)