Load an html5 canvas into a PIL Image with Django

前端 未结 4 1571
孤独总比滥情好
孤独总比滥情好 2020-12-15 09:54

I\'m trying to get the contents of an html5 canvas and pass it to my django server, where it will then be manipulated with PIL and saved as a PNG. Here\'s what I have so far

4条回答
  •  一向
    一向 (楼主)
    2020-12-15 10:14

    HTML:

    {% csrf_token %}

    Javascript:

    function submit_pixels(canvas) {
        $('form input[name=image_data]').val(canvas.toDataURL("image/png"));
        $('form input[name=width]').val(canvas.width);
        $('form input[name=height]').val(canvas.height);
        $('form').submit();
    }
    

    Django POST Request View:

    # in the module scope
    from io import BytesIO
    from PIL import Image
    import re
    import base64
    
    # in your view function
    image_data = request.POST['image_data']
    image_width = int(request.POST['width'])
    image_height = int(request.POST['height'])
    image_data = re.sub("^data:image/png;base64,", "", image_data)
    image_data = base64.b64decode(image_data)
    image_data = BytesIO(image_data)
    im = Image.open(image_data)
    assert (image_width, image_height,) == im.size
    

    Bump up the maximum POST size in your settings (example: ~20 MB):

    # canvas data urls are large
    DATA_UPLOAD_MAX_MEMORY_SIZE = 20_000_000
    

提交回复
热议问题