@
@
@messageman2020-10-11 18:13:14
Django
@messageman, 2020-10-11 18:13:14

How to change image after upload in Django?

I have a model ( https://pastebin.com/18W4AGSu )
The resize method is supposed to take an existing file from the 'ImageField', resize it and load it into the 'image_resized' field, but for some reason the ResizedForm is passing height arguments and model width, but nothing happens.
What do I need to do in order for resizing to work correctly? I'm sure I did something wrong somewhere

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
reqww, 2020-10-13
_

from PIL import Image
from io import BytesIO
from django.core.files.uploadedfile import InMemoryUploadedFile

def save_image(output, name, format):
    return InMemoryUploadedFile(
            output, 
            'ImageField', 
            "%s.jpg" % name.split('.')[0], 
            f'image/{format}',
            sys.getsizeof(output), 
            None
        )


def image_save(self, *args, **kwargs):
        im2 = Image.open(self.avatar)
        im2 = im2.resize((50, 50))
        try:
            im2.save(output, format='JPEG', quality=100)
            format = 'jpeg'
        except OSError:
            im2.save(output, format='PNG', quality=100)
            format = 'png'
        output.seek(0)
        self.small_avatar = save_image(output, self.avatar.name, format)

Try something like this, I open the image here, reduce its size, you have 2 variables for this, then write it to the binary and save

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question