PIL obj to ImageField

29 views
Skip to first unread message

Robert Englund

unread,
Jan 22, 2022, 10:36:46 AM1/22/22
to Django users
Hello

I have big problems with saving PIL objects to imagefield.
see my code below.

There are many solutions when searching on Google but none work for me.

What is the easiest way to save an image from url to ImageField?

# return Pil image
def get_img_from_url(url):
    urllib.request.urlretrieve(url, settings.MEDIA_ROOT + "/sample.jpg")
    return PIL.Image.open(settings.MEDIA_ROOT + "/sample.jpg")

# it works
my_pil_img =get_img_from_url(url)

mydata = {
     'imagetype': "B1",
     'original':  my_pil_img
     }

# does not work
form =ImagesForm(mydata)
form.save()

# models.Model
imagetype = models.CharField(blank=False, null=False, max_length=2, choices=IMAGE_TYPE, default='')
original = models.ImageField(default='img/default.jpg', upload_to=content_file_name, blank=False, null=False)  # Image orginal size
image = ImageSpecField(source='original',
                                 processors=[ResizeToFit(width=640)],
                                 format='JPEG',
                                 options={'quality': 60},
                                 autoconvert=True)

   square_thumbnail = ImageSpecField(source='original',
                            processors=[ResizeToFill(300, 300)],
                            format='JPEG', options={'quality': 60})
Reply all
Reply to author
Forward
0 new messages