skerdilajd hoxha
skerdilajd hoxha

Reputation: 73

PIL - saving image as .jpg not working

I'm trying to overwrite save() method of the model to resize images. Every format works, except when saving a .jpg image. It's not saving images with .jpg extension.

I read the Pillow documentation and there's no JPG format.

class Business(models.Model):
photo = models.ImageField(_('photo'), storage=OverwriteStorage(),
                          upload_to=image_upload_to, blank=True, null=True)


def save(self, **kwargs):
    """
    Changing dimensions of images if they are to big.
    Set max height or width to 800px depending on the image is portrait or landscape.
    """
    # Opening the uploaded image
    im = Image.open(self.photo)
    print(im)
    output = BytesIO()
    # set the max width or height
    im.thumbnail((800, 800))
    # find the ext of the file
    ext = self.photo.name.split('.')[1].upper()

    if ext in {'JPEG', 'PNG', 'GIF', 'TIFF'}:
        # after modifications, save it to the output
        im.save(output, format=ext, quality=100)
        output.seek(0)
        # change the imagefield value to be the newley modifed image value
        self.photo = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % self.photo.name.split('.')[0],
                                          'image/jpeg', sys.getsizeof(output), None)
        super(User, self).save()

I don't know what I am missing here.

And what's the best way to do this on a custom User model. Using a signal, overwriting ImageField or ...

Any help is appreciated :)

Upvotes: 2

Views: 5535

Answers (2)

Jason
Jason

Reputation: 933

Important: You can not save the files as a .jpg

You must use another extension such as .jpeg

Example: You have to use the Image object you import

from PIL import Image 

def image_ex():
     imagefile = 'images/original-image.jpg'
     new_name = os.path.splitext('{}'.format(filename))[0]+'.jpeg'

     Image.open(imagefile).rotate(270).filter(ImageFilter.DETAIL).save(new_name)

image_ex()

That works. Just remember dont save as a .jpg file extensions.

Upvotes: 0

Antoine Pinsard
Antoine Pinsard

Reputation: 35042

You handled extension JPEG, but not JPG.

You may handle it simply with something like that before your if:

if ext == 'JPG':
    ext = 'JPEG'

Upvotes: 4

Related Questions