Decoding base64 from POST to use in PIL

前端 未结 4 1750
感动是毒
感动是毒 2020-12-08 04:43

I\'m making a simple API in Flask that accepts an image encoded in base64, then decodes it for further processing using Pillow.

I\'ve looked at some examples (1, 2,

4条回答
  •  误落风尘
    2020-12-08 05:12

    Sorry for necromancy, but none of the answers worked completely for me. Here is code working on Python 3.6 and Flask 0.13.

    Server:

    from flask import Flask, jsonify, request
    from io import BytesIO
    from web import app
    import base64
    import re
    import json
    from PIL import Image
    
    @app.route('/process_image', methods=['post'])
    def process_image():
        image_data = re.sub('^data:image/.+;base64,', '', request.form['data'])
        im = Image.open(BytesIO(base64.b64decode(image_data)))
        return json.dumps({'result': 'success'}), 200, {'ContentType': 'application/json'}
    

    Client JS:

    // file comes from file input
    var reader = new FileReader();
    reader.onloadend = function () {
        var fileName = file.name;
        $.post('/process_image', { data: reader.result, name: fileName });
    };
    reader.readAsDataURL(file);
    

提交回复
热议问题