[Django]-Using fileReader.readAsDataURL to transport image through Ajax in Django and open in PIL

2👍

The filereader.readAsDataURL function produces a data URL which is a unicode string of the form “data:[image type];[encoding],[THEENCODEDSTUFF….]”.

To process it in python and possibly assign it to an image field, cherry pick from my code snippet below (the uploaded data is on the variable url_data and the imagefield on the django model object is 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()

Leave a comment