ajax - 在 Django 中使用 fileReader.readAsDataURL 通过 Ajax 传输图像并在 PIL 中打开

标签 ajax json django python-imaging-library

几天都打不过的问题。我需要通过 AJAX 将图像作为 JSON 传输。我使用 fileReader.readAsDataURL 将其编码为 base64,然后进行传输。但是PIL不会打开它。这是我的代码:

脚本.js:

function imageloader(callBack){
var input = $('#photo');
var file = input.prop('files')[0];
var reader = new FileReader();
reader.onload = function(){
    callBack(reader.result);

};
reader.readAsDataURL(file);

$('#edit_form').submit(function (eve) {
    eve.preventDefault();
    var form = $.toJSON($(this).serializeArray());
    imageloader(function(image){
        var image_data = $.toJSON(image);
        sender(form,image_data);
    });
});    

View .py:

def post(self, request):
    form = request.POST.get('form')
    image = request.POST.get('image')
    new_image = json.loads(image)
    data = json.loads(form)
    new_data = {}
    for i in data:
        new_data[i['name']] = i['value']
    new_data['photo'] = resize_picture(new_image)
...
def resize_picture(file):
    file = file.split(',')[1]
    bytes = (BytesIO(base64.b64decode(file)))
    bytes.seek(0)
    image = bytes.read()
    img = Image.open(image)
    img.thumbnail(IMAGE_SIZE, Image.ANTIALIAS)
    return img

每次尝试时,我都会从 PIL 尝试打开文件时收到此错误:

 file() argument 1 must be encoded string without NULL bytes, not str 

我错过了什么吗?

最佳答案

filereader.readAsDataURL 函数生成一个数据 URL,它是一个 unicode 字符串,格式为“data:[image type];[encoding],[THEENCODEDSTUFF....]”。

要在 python 中处理它并可能将其分配给图像字段,请从我下面的代码片段中挑选(上传的数据在变量 url_data 上,django 模型对象上的图像字段是 obj.avatar_image):

    img_dict = re.match("data:(?P<type>.*?);(?P<encoding>.*?),(?P<data>.*)", url_data).groupdict()
    blob = img_dict['data'].decode(img_dict['encoding'], 'strict')
    image = Image.open(StringIO(blob))
    image = image.resize((75, 75), Image.ANTIALIAS)
    f = StringIO()
    try:
        image.save(f, format='png')
        filename = os.path.splitext(filename)[0] + '.png'
        obj.avatar_image.save(filename, ContentFile(f.getvalue()))
    finally:
            f.close()

关于ajax - 在 Django 中使用 fileReader.readAsDataURL 通过 Ajax 传输图像并在 PIL 中打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31318190/

相关文章:

java - 如何确定 ConstraintViolation 是来自 JSON 属性还是来自 URL 参数?

json - 我们可以将电子邮件 ID 作为 Firebase 数据库中的键吗?

python - 将一系列外键串在一起以返回 Django 中的表值

python - 在 django 中为模型编写自定义更新方法

php - iframe 的 SEO 友好替代方案?

php - jquery $.get() 返回 [object,object]

在 Ruby On Rails 中使用幻灯片放映的 jQuery

python - Django REST Framework 过滤多个字段

php - 在 PHP 中,在数组中搜索包含子字符串的值的快速方法是什么?

javascript - Html 表格行未附加到指定的表格