Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

Django Save Image

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
Comment

PREVIOUS NEXT
Code Example
Python :: how to find if the numpy array contains negative values 
Python :: how to cout in python 
Python :: move items from one list to another python 
Python :: Converting Hex to RGB value in Python 
Python :: dict typing python 
Python :: python all lowercase letters 
Python :: numpy vector multiplication 
Python :: python save image to pdf 
Python :: arrange array in ascending order python 
Python :: add fonts to matplotlib from a particular location 
Python :: cv2.namedWindow 
Python :: how to convert array to vector in python 
Python :: python timedelta to seconds 
Python :: How to Count occurrences of an item in a list in python 
Python :: python asctime 
Python :: setting urls 
Python :: keep only one duplicate in pandas 
Python :: how to add two numbers 
Python :: numpy save multiple arrays 
Python :: python format subprocess output 
Python :: wait driver selenium 
Python :: kivymd window size 
Python :: unittest skip 
Python :: writerows to existing csv python 
Python :: isaplha in python 
Python :: how to convert a list to dataframe in python 
Python :: one line if statement no else 
Python :: tab of nbextensions not showing in jupyter notebook 
Python :: python while loop 
Python :: python 
ADD CONTENT
Topic
Content
Source link
Name
6+8 =