【问题标题】:Python flask upload base64 image [duplicate]Python烧瓶上传base64图像[重复]
【发布时间】:2017-04-09 09:48:16
【问题描述】:

我正在尝试在 JS(使用 cropit)和 Python(Flask) 中创建裁剪和调整大小工具

Cropit 返回裁剪图像的 base64,我通过 AJAX 将其发送到服务器,但无法保存。

阿贾克斯:

$.ajax({
                type: 'GET',
                url: '/api/saver',
                data: 'file=' + imageData,
                enctype: 'multipart/form-data',
                processData: false,  // Important!
                contentType: 'application/json;charset=UTF-8',
                cache: false,
                success: function(msg){
                    console.log('Done')
                }
            });

在服务器端

@app.route('/api/saver/', methods=['GET', 'POST'])
def api_save_base64_image():
    if request.method == 'GET':
        file = request.args.get('file')
        starter = file.find(',')
        image_data = file[starter+1:]
        image_data = bytes(image_data, encoding="ascii")
        with open('.../image.jpg', 'wb') as fh:
            fh.write(base64.decodebytes(image_data))
        return 'ok'
    return 'error

无异常返回,但 image.jpg 已损坏(空)。

如何通过 Flask 从客户端保存图像?

【问题讨论】:

  • 检查你的base64!该代码适用于正确的数据

标签: javascript python ajax flask base64


【解决方案1】:

这有点棘手 :) 但是cropit 将图像导出为png

数据:图像/png

因此,如果您将代码更改为此,它的工作原理:)

with open('image.png', 'wb') as fh:
    fh.write(base64.decodebytes(image_data))

要更改格式,您可以这样做:

import base64
from io import BytesIO
from PIL import Image

...

        image_data = bytes(image_data, encoding="ascii")
        im = Image.open(BytesIO(base64.b64decode(image_data)))
        im.save('image.jpg')

...

您可以在image_stof.py中找到此代码和数据

【讨论】:

  • 你知道通过烧瓶保存裁剪的 base64 图像的更简单方法吗?更改了图像格式,但结果相同 - yadi.sk/i/n4V3bPRM3GnjxG
  • 请检查答案!我更新了它,你可以在我的 GitHubs Gits 中找到并测试它
  • return binascii.a2b_base64(s) binascii.Error: Incorrect padding or - raise IOError(message + " when reading image file") OSError: broken data stream when reading image file
  • 谢谢,base64.encodebytes() 方法对我有用。
猜你喜欢
  • 1970-01-01
  • 2019-06-21
  • 2021-06-28
  • 1970-01-01
  • 1970-01-01
  • 2018-06-05
  • 2018-07-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多