- 在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>
保存文件.py
#!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,))
**预期输出:**它应该显示从指定路径获取的图像。
**实际输出:**显示带有文本的img块C:/Apache24/htdocs/tmp/xy.jpg
2条答案
按热度按时间tjvv9vkg1#
最后解决方案在于图像格式不在文件路径中的问题...
这是针对您的PIL中缺少JPEG支持的原因。这里介绍了我的解决方案。https://apple.stackexchange.com/questions/59718/python-imaging-library-pil-decoder-jpeg-not-available-how-to-fix
转到here下载liblibjpeg软件包。或者
6mzjoqzu2#
如果你只想用HTML显示图片,并且它的路径是用python指定的,你可以使用python web框架,比如flask,来简化这一过程。
注意:Path是变量,您可以从python传递它。