【问题标题】:Error while displaying base64 encoded images in an html page在 html 页面中显示 base64 编码图像时出错
【发布时间】:2018-10-09 22:17:48
【问题描述】:

我有一个包含 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 是包含图像的列表

【问题讨论】:

    标签: html python-2.7 base64 python-imaging-library


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2017-04-24
      • 2015-11-22
      • 2013-11-17
      • 2015-03-07
      • 2013-04-16
      • 1970-01-01
      • 2011-09-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多