在python中显示指定到HTML浏览器的路径的图像。我已经用这种方式编码了。
的index.html
<html>
<body>
<form enctype = "multipart/form-data"
action = "save_file.py" method = "post">
<p>File: <input type = "file" name = "filename" /></p>
<p><input type = "submit" value = "Upload" /></p>
</form>
</body>
</html>
save_file.朋友
#!C:/Users/Vitriv-Desktop/AppData/Local/Programs/Python/Python36-32/python.exe
import cgi, os
import cgitb; cgitb.enable()
from PIL import Image
form = cgi.FieldStorage()
# Get filename here.
fileitem = form['filename']
# Test if the file was uploaded
if fileitem.filename:
# strip leading path from file name to avoid
# directory traversal attacks
fn = os.path.basename(fileitem.filename)
open('C:/Apache24/htdocs/tmp/' + fn, 'wb').write(fileitem.file.read())
message = 'The file "' + fn + '" was uploaded successfully'
path = 'C:/Apache24/htdocs/tmp/' + fn
image = Image.open('C:/Apache24/htdocs/tmp/' + fn)
image.show()
else:
message = 'No file was uploaded'
#Content-Type: text/html\n
print ("""\
Content-Type: image/jpg\n
<!DOCTYPE html>
<html>
<body>
<p>%s </p>
<img src="%s" alt="C:/Apache24/htdocs/tmp/%s">
</body>
</html>
""" % (message,path,fn,))
预期输出:应显示指定路径的图像。 实际输出:使用带文本C的img块显示:/Apache24/htdocs/tmp/xy.jpg
最后解决方案在于图像格式不在文件路径问题中......
这是你在PIL中缺少的JPEG支持,这是我在这里解释的解决方案。 https://apple.stackexchange.com/questions/59718/python-imaging-library-pil-decoder-jpeg-not-available-how-to-fix
转到here下载lib libjpeg包。要不就
brew install libjpeg
如果您只想使用HTML显示图像并在python中指定其路径,则可以使用python Web框架(如烧瓶)轻松实现。
<label class="col-sm-2 control-label">Display Picture</label>
<img id="output" name="img" alt="Display Picture" src="
{{url_for('static',filename=path)}}" />
注意:Path是可变的,你可以从python传递它。