1

I'm trying to create crop and resize tool in JS (use cropit) and Python(Flask)

Cropit returned base64 of cropped image, i sending it via AJAX to server, but can't save it.

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')
                }
            });

On the server side

@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

Returned without exceptions, but image.jpg is broken (empty).

How i can save images from client side via Flask?

Konstantin Rusanov
  • 6,414
  • 11
  • 42
  • 55

1 Answers1

3

It's kind of tricky :) but cropit export image as png

data:image/png

So if you change your code to this, It's works :)

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

For change format you can do this:

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')

...

You can find this code with data in image_stof.py

Community
  • 1
  • 1
RaminNietzsche
  • 2,683
  • 1
  • 20
  • 34