如何使用python将图像显示为HTML

cwdobuhd  于 2023-01-28  发布在  Python
关注(0)|答案(2)|浏览(715)
  • 在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

tjvv9vkg

tjvv9vkg1#

最后解决方案在于图像格式不在文件路径中的问题...

这是针对您的PIL中缺少JPEG支持的原因。这里介绍了我的解决方案。https://apple.stackexchange.com/questions/59718/python-imaging-library-pil-decoder-jpeg-not-available-how-to-fix
转到here下载liblibjpeg软件包。或者

brew install libjpeg

6mzjoqzu

6mzjoqzu2#

如果你只想用HTML显示图片,并且它的路径是用python指定的,你可以使用python web框架,比如flask,来简化这一过程。

<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传递它。

相关问题