html - 在 html 页面中显示 base64 编码图像时出错
问题描述
我有一个包含 base64 编码图像的列表:
当我尝试在 HTML 页面中显示列表中的图像时,它只连续显示第一张图像。当我打印列表中的每个元素时,我看到第一个编码名称被第二个编码名称填充。
例如:
如果第一个编码图像的名称是“first”,那么第二个编码的名称是“firstsecond”,第三个将是“firstsecondthird”,就像它重复到列表中的最后一个图像一样。
我的编码代码是:
img = Image.open(os.path.join(upload,filename))
cropped = img.crop( ( left, top, right, bottom ) )
cropped.save(buffer, "PNG")
img_str = base64.b64encode(buffer.getvalue())
crop_pic.append(img_str)
我的html代码是:
<table>
{% for i in crop_pic: %}
<tr>
<td>
<img src="data:image/png;base64,{{ i }}">
</td>
</tr>
{% endfor %}
</table>
crop_pic 是包含图像的列表
解决方案
问题是在循环继续时第一个图像的名称用第二个填充,为了避免这种情况,我在将每个图像附加到列表后删除了变量 img_str 和缓冲区。所以代码将是这样的:
for top, right, bottom, left in boxes:
buffer = StringIO.StringIO()
img = Image.open("path/to/file")
cropped = img.crop( ( left, top, right, bottom ) )
cropped.save(buffer, "PNG")
img_str = base64.b64encode(buffer.getvalue())
crop_pic.append(img_str)
del img_str, buffer
所以在运行这段代码后,我在 html 页面中显示时没有得到相同的图像。
推荐阅读
- c# - Unity: InvalidProgramException: Invalid IL code XXX(): IL_0011
- c# - 如何重定向到具有 2 个参数的页面
- python - 在 Pythonic 库设计中正确导入包?
- vim - 如何在多个文件中组织内容 .vimrc
- c++ - 将函数应用于特征矩阵中的所有元素,无需循环
- javascript - Google Scripts 中的序数日期格式(th、rd、st、nd)
- python-3.x - 如何在 Bash 脚本上运行带有参数的 Python
- django - Django:如何在外键仪表板上添加约束
- optimization - 用于线性化、求解器优化的嵌套 if 函数变换
- python - 将 R 代码转换为 python 代码