【问题标题】:Load an html5 canvas into a PIL Image with Django and save it in new File使用 Django 将 html5 画布加载到 PIL 图像中并将其保存在新文件中
【发布时间】:2026-01-29 00:35:01
【问题描述】:

我测试了这个例子:问题来源:Load an html5 canvas into a PIL Image with Django

import re

datauri =  'data:image/png;base64,iVBORw0KGgoAAAANSUhEUg
AAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8  /w38GIAXDIBKE0DHxgl
jNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='

imgstr = re.search(r'base64,(.*)', datauri).group(1)

output = open('output.png', 'wb')

output.write(imgstr.decode('base64'))

output.close()

但我在这一行有一个错误:

output.write(imgstr.decode('base64'))

这里是错误:文件“C:\django_projects\intranet\intranet\capture\views.py”,第 19 行,在 enregistre_image output.write(imgstr.decode('base64')) AttributeError: 'str' object没有“解码”属性

你能告诉我我做错了什么吗谢谢克里斯托夫

【问题讨论】:

    标签: django python-imaging-library


    【解决方案1】:

    您的代码在 中运行良好(您可能在 Python 中搜索了一个解决方案,并得到了在 中运行的版本)。

    中,string 不再有.decode(..) 方法。您可以使用base64 库:

    from base64 import b64decode
    output.write(b64decode(imgstr))

    【讨论】:

    • 谢谢 Willem,我在 python 3.x 中,现在可以正常工作了