Loading Base64 String into Python Image Library

11,800

Solution 1

SOLUTION:

Saving the opened PIL image to a file-like object solves the issue.

pic = cStringIO.StringIO()
image_string = cStringIO.StringIO(base64.b64decode(request.POST['file']))
image = Image.open(image_string)
image.save(pic, image.format, quality = 100)
pic.seek(0)
return HttpResponse(pic, content_type='image/jpeg')

Solution 2

The beginning of the POSTed string (data:image/jpeg;base64,) is a header and should be removed before the decoding. The image is corrupted otherwise.

photo = request.POST['photo'].partition('base64,')[2]
image_data = b64decode(photo)
someobject.photo.save('user.jpg', ContentFile(image_data), save=True)
Share:
11,800
Praveen
Author by

Praveen

Updated on July 18, 2022

Comments

  • Praveen
    Praveen almost 2 years

    I'm sending images as base64 string through ajax to django. In my django view I need to resize the image and save it in the file system.

    Here is a base64 string(simplified):

    data:image/jpeg;base64,/9j/4AAQSkZJRg-it-keeps-going-for-few-more-lines=
    

    I tried to open this in PIL using the below python code:

    img = cStringIO.StringIO(request.POST['file'].decode('base64'))
    image = Image.open(img)
    return HttpResponse(image, content_type='image/jpeg')
    

    I'm trying to display the uploaded image back, but firefox complains that 'The image cannot be displayed because it contains error'

    I couldn't figure out my mistake.

    SOLUTION:

    pic = cStringIO.StringIO()
    
    image_string = cStringIO.StringIO(base64.b64decode(request.POST['file']))
    
    image = Image.open(image_string)
    
    image.save(pic, image.format, quality = 100)
    
    pic.seek(0)
    
    return HttpResponse(pic, content_type='image/jpeg')
    
  • Dominique PERETTI
    Dominique PERETTI over 9 years
    This solution seems wrong. Using PIL, one forces the image to be saved as a valid JPEG, which it is not (see my answer below)? So it's probably slightly corrupted but one cannot notice it.