Python在HTML中显示服务器端图像

0 投票
1 回答
1421 浏览
提问于 2025-04-17 19:27

我在服务器的文件夹里有一张图片。在我的 do_GET() 函数中,这个函数负责处理获取请求,我想把这张图片发回去。我选择使用 self.wfile.write('')。有没有人能告诉我怎么把图片的来源放进 img 标签里?或者有没有更好的方法?谢谢。

1 个回答

1

你可以在图片标签中使用数据URI来包含图片的“来源”,方法如下:

<img alt="Embedded Image" src="data:image/png;base64,<your base64 encoding here>" />

你可以用Python的标准库来生成这个base64字符串,具体方法是:

import base64

with open("image.png", "rb") as image:
    encoded_string = base64.b64encode(image.read())

撰写回答