Share with   

Compress or reduce size of image using Django rest framework

Here we are compressing the image size or reducing image size to store low size image in server using python Byte IO and Django rest framework.


Django Image Compression

Image compression is minimizing the size of the current image size without reducing the quality of the image.

It helps to optimize the storage of server to add more image with goodest quality.

How to compress image in django python web framework?

To compress image in django web framework we need some libraries install into django project environment.

 

Prerequisite

  1. Install Python
  2. Install Django

 

Setup

Create Python Virtual Environment

mkvirtualenv json_response_demo

Install Django

pip install django pillow

Create Django Project

django-admin startproject EmployeeData

Create Django App

django-admin startapp api

Register api app in django settings install apps.

# EmployeeData > EmployeeData > settings.py
INSTALLED_APPS = [
	    'django.contrib.admin',
	    'django.contrib.auth',
	    'django.contrib.contenttypes',
	    'django.contrib.sessions',
	    'django.contrib.messages',
	    'django.contrib.staticfiles',
	    'api',
	]

Create Model for movie collection todo list django app

# models.py file in api direcotry

from django.db import models

def upload_location(instance, filename, **kwargs):
    file_path = 'movie_picture/{filename}'.format(filename=filename)
    return file_path

class Movie(models.Model): 
    title = models.CharField(max_length=32)
    content = models.TextField()
    year = models.IntegerField()
    picture = models.ImageField(
        upload_to=upload_location, null=False, blank=True)
    
    def save(self,force_insert=False, force_update=False, using=None,*args, **kwargs):
        if self.picture:
            image = self.picture
            if image.size > 0.3*1024*1024: #if size greater than 300kb then it will send to compress image function
                self.picture = compress_image(image)
        super(Movie, self).save(*args, **kwargs)


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

def compress_image(image):
    im = Image.open(image)
    if im.mode != 'RGB':
        im = im.convert('RGB')
    im_io = BytesIO()
    im.save(im_io, 'jpeg', quality=70,optimize=True)
    new_image = File(im_io, name=image.name)
    return new_image

Pillow library is used to perform operation of images in python.

BytesIO is used to read the image for changing the quality of image.

We have successfully created image compression in django rest framework in python language.

Author Image
Guest User

0 Comments