Search code examples
djangopython-imaging-librarystringio

Django. Download Image with requests - edit with PIL - save to model


I'm having trouble with this process: I want to download an image using requests, then crop it with PIL and then save it to the a model ImageField.

This is what I have now:

from django.core.files.base import ContentFile
import requests
from StringIO import StringIO
from PIL import Image


def get_img_url(url_img):
    answer = requests.get(url_img)
    image = Image.open(StringIO(answer.content))
    new_image = image.crop((22, 44, 221, 165))

    return image


class FormNewCard(forms.ModelForm):

....

    def save(self, **kwargs):

        url_image = self.cleaned_data['imagen']
        pil_img = get_img_url(url_img)
        stringio_obj = StringIO()
        try:
            pil_img.save(stringio_obj, format="JPG")
            final_image = stringio_obj.getvalue()
            self.image = ContentFile(final_image)
        finally:
            stringio_obj.close()

I get this error:

       pil_img.save(stringio_obj, format="JPG")

       KeyError at /hisoka/new_card/
       'JPG'

I know the error is purely a PIL problem, I'm not sure how to solve it (tried several times), but also, I'd like to know if what I'm doing is correct or if there is a better way to achieve this.


Solution

  • Since, you get a KeyError with the key being 'JPG', it's fairly certain that Pillow doesn't recognize it.

    But if you have a look at the docs, you'll notice that it is spelled JPEG. Hence, simply set format='JPEG'.