Программисты Html
Anonymous
Как отобразить изображение в HTML с помощью Python
Сообщение
Anonymous » 24 янв 2026, 02:00
Чтобы отобразить изображение по указанному пути в HTML-браузере в Python. Я написал код таким образом.
index.html
save_file.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
%s
[img]%s[/img]
""" % (message,path,fn,))
Ожидаемый результат: должно отображаться изображение, полученное по указанному пути.
Фактический результат: Отображение с блоком img с текстом C:/Apache24/htdocs/tmp/xy.jpg
Подробнее здесь:
https://stackoverflow.com/questions/479 ... ing-python
1769209215
Anonymous
Чтобы отобразить изображение по указанному пути в HTML-браузере в Python. Я написал код таким образом. index.html [code] File: [/code] [b]save_file.py[/b] [code]#!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 %s [img]%s[/img] """ % (message,path,fn,)) [/code] [b]Ожидаемый результат:[/b] должно отображаться изображение, полученное по указанному пути. [b]Фактический результат:[/b] Отображение с блоком img с текстом C:/Apache24/htdocs/tmp/xy.jpg Подробнее здесь: [url]https://stackoverflow.com/questions/47937366/how-to-display-image-to-html-using-python[/url]