首页 > 解决方案 > 在 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 是包含图像的列表

标签: htmlpython-2.7base64python-imaging-library

解决方案


问题是在循环继续时第一个图像的名称用第二个填充,为了避免这种情况,我在将每个图像附加到列表后删除了变量 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 页面中显示时没有得到相同的图像。


推荐阅读