S
S
Sergey Nizhny Novgorod2017-07-22 15:48:53
Django
Sergey Nizhny Novgorod, 2017-07-22 15:48:53

How to get a PIL object to save into a Django model?

Hello everyone
. I'm making a smart crop, I'm trying to save it in shape, but I don't understand how to pull out the desired object.
models.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    avatar = models.ImageField(upload_to='', blank=True, null=True,)

forms.py
class Profile_Form(forms.Form):
    avatar = forms.ImageField(label='Загрузить Аватар', required=False)

views.py I receive
data from the client, where they tell me what image dimensions to save as a result
from PIL import Image

if form.cleaned_data['avatar']:
  x = float(request.POST.get('x', ''))
  y = float(request.POST.get('y', ''))
  w = float(request.POST.get('width', ''))
  h = float(request.POST.get('height', ''))

  avatar = form.cleaned_data['avatar']

  image = Image.open(avatar)
  cropped_image = image.crop((int(x), int(y), int(w+x), int(h+y)))
  resized_image = cropped_image.resize((200, 200), Image.ANTIALIAS)
  useritem.profile.avatar = resized_image
        # На этом этапе у меня получается вот такой объект, как его свести в валидный для Django?
       #  <PIL.Image.Image image mode=RGB size=200x200 at 0x1144A70>

  useritem.profile.save(update_fields=['avatar'])

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2017-07-22
@Terras

from io import BytesIO
from django.core.files.base import ContentFile
from PIL import Image

file_buffer = BytesIO()
resized_image.save(file_buffer, 'png')

useritem.profile.avatar.save(useritem.username + '_avatar.png', ContentFile(file_buffer.read()))
useritem.profile.save()

file_buffer.close()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question