Home > Blockchain >  Django image saving
Django image saving

Time:05-25

I wonder what is the best practices in saving images into ImageField in Django?

class Image(models.Model):
    image = ...

    def save(self, *args, **kwargs):
        ... # resizing and saving the image
        super().save(*args, **kwargs)

I want to save images but not in original size. I want to save only the resized image. As far as I know the super save method here additionally saves the original image to database. But I want it to save only resized to prevent data overflow. How to do that?

CodePudding user response:

you can do it in the following way I'll put the functions here, but you can put them in another file to reuse them and then import them, I'll add the necessary libraries

import PIL
from io import BytesIO
from PIL import Image
from django.core.files import File



class Image(models.Model):
    image = models.FileField()

    def save(self, *args, **kwargs):
        new_image = self.compress_images(self.image)  
    
        # asignar la nueva imagen con menor peso
        self.image = new_image
        super().save(*args, **kwargs)
   

    def valid_extension(self,_img):
        if '.jpg' in _img:
            return "JPEG"
        elif '.jpeg' in _img:
            return "JPEG"
        elif '.png' in _img:
            return "PNG"


    def compress_images(self,image):
        im = Image.open(image)
        width, height = im.size
        im = im.resize((width-50, height-50), PIL.Image.ANTIALIAS) 
        # crear a BytesIO object
        im_io = BytesIO() 
        im.save(im_io, self.valid_extension(image.name) ,optimize=True, 
        quality=70) 
        new_image = File(im_io, name=image.name)
        return new_image
  • Related