I have a Flask server and I want to render a base64 image in HTML page.
Flask Code:
new_image_string = base64.b64encode(buff.getvalue()).decode("utf-8")
return render_template('perspective_result.html', img_data=new_image_string)
HTML CODE:
<img src="data:image/jpeg;base64,+img_data" alt="img_data" id="imgslot"/>
I am getting the below error from browser console:
GET data:image/jpeg;base64,+img_data 0 ()
Where did I go wrong?
<img src="data:image/jpeg;base64,{{ img_data }}" alt="img_data" id="imgslot"/>
This is the way we can solve this.
1.First Add A empty Image Tag Without A Source
2.Then With Javascript preprocess the base64 data string
3.update the Image src with updated base64 data
<img src="" id="img" alt="Chart" height="100" width="100">
<script>
data = "{{data}}"
data = data.replace("b'", "") //to get rid of start curly brace code
data = data.replace("'", "") //to get rid of end curly bracecode
document.getElementById("img").src = "data:image/png;base64,"+data; // set src
</script>
Related
I'm looking to display a blob stored in a MySQL table within an HTML, using python-flask. But i am getting the broken image icon on the webpage when i run the code. The string data renders just fine, but not the blob. The web developer tool is indicating a 404 error when attempt to grab the blob resource, but i can't seem to make much of it. Looking for some help.
My Python code is:
#EMR.route("/apple")
def apple_luv():
t0 = gold.query.filter_by(patient_id=101).first()
tx = t0
return render_template("apple.html", t1=tx)
and HTML is shown below (FYI: tried a few syntaxes with the img tag since i was unsure)
<body>
{{t1.patient_fname}} | {{t1.patient_lname}} | {{t1.patient_addr}}
<br><br><br>
<img src="{{t1.patient_pic}}" />
<br><br><br>
<img src={{t1.patient_pic}} />
<br><br><br>
<img src="{{t1.patient_pic}}" >
<br><br><br>
<img src={{t1.patient_pic}} >
</body>
See the attachments for what my data looks like in MySQL DB, and the webpage outcome as well.
return render_template('homepage.html',imgName=filenameD)
PYTHON
<img src= {{ name }} alt="something" style="width:500px;height:600px;">
HTML
im trying to change the image on my website based on the data I pass to it with python flask but the image does not show up, im using something called jinja?
The image is not shown because you are referencing a non-existent variable in your template. Change your <img> tag to
<img src="{{ imgName }}" alt="something" style="width:500px;height:600px;">
and make sure that filenameD contains the path to your image and not only its name i.e. it should be something like /static/image.png.
Also, always surround your attribute values with "" to prevent XSS attacks, see Flask's security docs.
Try this:
Python
return render_template('homepage.html',name=filename)
HTML
<img src = "{{url_for('static', filename=name) }}" alt="something" style="width:500px;height:600px;">
Your image must be located inside 'static' folder and named as usually ('myimg.png', etc)
I'm trying to show some badge images I made for a RANK APP I've been working for. It's 10 images that should be shown specific for each driver.
I'm not an expert on coding, but I keep searching and studying ways to solve the problem I've been through.
I firstly tried to send base64 images from the API to the browser, using this code:
<!-- language: python -->
for img in imglist: #loop for creating a list of base64 images from a list of image dir.
imgcode = base64.encodestring(open(imgdir + img,"rb").read())
imgcodelist.append(imgcode)
for driver in sortdriverList: #loop for taking drivers points and turn it into RANK img
if (driver['Races'] < 21):
driver['Rank'] = str(imgcodelist[9])
[...]
The second loop is longer than that, stil what I've shown to you above makes any driver that wasn't participating in more than 21 races, be part of a 'NON CLASSIFIED' badge.
I used AngularJS to try to show the base64 image using the code below.
'<html>'
<td><img src="data:image/png;base64,{{ '{{driver.Rank}}'}}"></td>
[driver.Rank] should be the base64 code string. When I run the app, the image is not shown, instead I see the very code of the image inside the table =/
Then I tried to turn [driver.Rank] into a dir string for "img src=", using the codes below.
<!-- language: python -->
imglist = ["notclassified.png", etc...]
imgdir = "static/images/"
for item in sortdriverList:
if (item['Races'] < 21):
item['Points'] = imgdir + imglist[9]
and in my HTML I changed the img src to:
'<html>'
<img src= {{ '{{driver.Rank}}' }}>
and now it shows the directory of the images.
I've been searching for CSS ways to make it possible.
I coudn't find a solution yet.
It's hard to tell what's going on since only segments are pasted, but I'm guessing it has to do with how you are escaping the code. Maybe you could paste the generated code in chrome.
Sometimes seeing a working example helps.
angular.module('App', [])
.controller('DriverCtrl', DriverCtrl);
function DriverCtrl($scope) {
// base64 encode 1x1 black pixel
this.Rank = 'R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs=';
}
<div ng-app="App">
<div ng-controller="DriverCtrl as driver">
<div>Rank: {{driver.Rank}}</div>
<span>Image:</span>
<img ng-src="data:image/png;base64,{{driver.Rank}}">
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
I'm trying to save a chart by converting SVG to PNG with a Python script.
So I start storing the svg data in a variable with :
var svgdata = Ext.draw.engine.SvgExporter.generate(chart.surface);
When I do alert(svgdata), I can see that this output is correct.
But when I send it to the server like this :
Ext.draw.engine.ImageExporter.defaultUrl = "data/svg_to_png.py?svgdata="+svgdata;
The svgdata that has been sent looks like this :
<?xml version=
I'm new to extjs, please help me on this one. What is the right way to send svg data to my python script and render a png image ?
This is my python script :
import cairo
import cgi
import rsvg
print "Content-type: image/png\n\n"
arguments = cgi.FieldStorage()
img = cairo.ImageSurface(cairo.FORMAT_ARGB32, 640,480)
ctx = cairo.Context(img)
handler= rsvg.Handle(None, str(arguments["svgdata"]))
handler.render_cairo(ctx)
img.write_to_png("svg.png")
HELP ME PLEASE!
<div style="display:none;">
<iframe id="file_download_iframe" src="blank.html"></iframe>
</div>
You will need a blank html page on your server for this to work properly in all browsers. Basically the blank.html page is an empty page to satisfy that the ifram always has a page in it.
Then you need a basic form hidden somewhere too:
<div style="display:none;">
<form
id = "file_download_iframe_form"
name = "file_download_iframe_form"
target = "file_download_iframe"
method = "post"
action = "data/svg_to_png.py"
>
<input type="hidden" id="svgdata" name="svgdata"/>
</form>
</div>
Then have a javascript function like this:
function getImage(svgdata){
var form = document.getElementById("file_download_iframe_form");
document.getElementById("svgdata").value = svgdata;
form.submit();
};
I have a webpage generated from python that works as it should, using:
print 'Content-type: text/html\n\n'
print "" # blank line, end of headers
print '<link href="default.css" rel="stylesheet" type="text/css" />'
print "<html><head>"
I want to add images to this webpage, but when I do this:
sys.stdout.write( "Content-type: image/png\n\n" + file("11.png","rb").read() )
print 'Content-type: text/html\n\n'
print "" # blank line, end of headers
print '<link href="default.css" rel="stylesheet" type="text/css" />'
...
All I get is the image, then if I place the image code below my html/text header all I get is the text from the image, ie:
<Ï#·öÐδÝZºm]¾|‰k×®]žòåËÛ¶ÃgžyFK–,ÑôéÓU½zuIÒ}÷ݧ&MšH’V¯^?üð¼1±±±zýõ×%IñññÚºu«*W®¬wß}W.—K3gÎÔÌ™ÿw‹Ú””I’¹w¤¥hdÒd½q÷X•Šˆ²m¿þfïÞ½*]º´éÈs;¥¤¤Ø¿ILLÔˆ#rÊ
Also, if I try:
print "<img src='11.png'>"
I get a broken image in the browser, and browing directly to the image produces a 500 internal server error, with my apache log saying:
8)Exec format error: exec of './../../11.png' failed Premature end of script headers: 11.png
You can use this code to directly embed the image in your HTML:
Python 3
import base64
data_uri = base64.b64encode(open('Graph.png', 'rb').read()).decode('utf-8')
img_tag = '<img src="data:image/png;base64,{0}">'.format(data_uri)
print(img_tag)
Python 2.7
data_uri = open('11.png', 'rb').read().encode('base64').replace('\n', '')
img_tag = '<img src="data:image/png;base64,{0}">'.format(data_uri)
print(img_tag)
Alternatively for Python <2.6:
data_uri = open('11.png', 'rb').read().encode('base64').replace('\n', '')
img_tag = '<img src="data:image/png;base64,%s">' % data_uri
print(img_tag)
Images in web pages are typically a second request to the server. The HTML page itself has no images in it, simply references to images like <img src='the_url_to_the_image'>. Then the browser makes a second request to the server, and gets the image data.
The only option you have to serve images and HTML together is to use a data: url in the img tag.
You can't just dump image data into HTML.
You need to either have the file served and link to it or embed the image encoded in base64.