DEV Community

Vinay Khatri
Vinay Khatri

Posted on

Compress Images size with Python

A high quality image comprise of many pixels which increase the image overall memory size. But sometime when we want to save the image in less quality for better loading, in that case we use the image compression. Image compression is a process where we minimize the size of the image without degrading the image quality.

To compress the Image in Python we can use the pillow library which is an open source third party library.
To use this library first we need to install for our Python environment using the pip install command.

pip install pillow
Enter fullscreen mode Exit fullscreen mode

After installing this library we can start compressing the image we want.

import PIL
from PIL import Image

#open the image
with  Image.open('original.jpg') as my_image:

    # the original width and height of the image
    image_height = my_image.height
    image_width = my_image.width

    print("The original size of Image is: ", round(len(my_image.fp.read())/1024,2), "KB")

    #compressed the image
    my_image = my_image.resize((image_width,image_height),PIL.Image.NEAREST)

    #save the image
    my_image.save('compressed.jpg')

    #open the compressed image
    with Image.open('compressed.jpg') as compresed_image:
        print("The size of compressed image is: ", round(len(compresed_image.fp.read())/1024,2), "KB")

Enter fullscreen mode Exit fullscreen mode

Output

The original size of Image is:  1953.24 KB
The size of compressed image is:  1547.01 KB
Enter fullscreen mode Exit fullscreen mode

compress the images using python
Break the code

  1. First load the original image that we want to comrpess using the Image.open() method.
  2. Find the width and the height of the original image, using the width and height properties.
  3. compress the image copy using the resize method, keep the daimension size of the compressed image as same as the original image and apply the PIL.Image.NEAREST filter to compressed the image in the my_image.resize((image_width,image_height),PIL.Image.NEAREST) statement. Note: There are multiple compression filter available for the resize mehtod you can check all the filters here.
  4. At last save the compressed image using the save() method.

Note: I used the

print("The original size of Image is: ", round(len(my_image.fp.read())/1024,2), "KB")
print("The size of compressed image is: ", round(len(compresed_image.fp.read())/1024,2), "KB")

statements to show the difference between the size of the original image and compressed image.

Resize the size

In the above code snippet we keep remain the dimension of the compressed image as same as the original image, which result in not that much of size difference. We can also resize the dimension size of the original image by specifying the specific width and height for the compressed image.

from turtle import width
import PIL
from PIL import Image

#open the image
with  Image.open('original.jpg') as my_image:

    #new widht and height in px
    width = 400
    height = 700

    print("The original size of Image is: ", round(len(my_image.fp.read())/1024,2), "KB")

    #compressed the image
    my_image = my_image.resize((width,height),PIL.Image.NEAREST)

    #save the image
    my_image.save('compressedResized.jpg')

    #open the compressed image
    with Image.open('compressedResized.jpg') as compresed_image:
        print("The size of compressed image is: ", round(len(compresed_image.fp.read())/1024,2), "KB")
Enter fullscreen mode Exit fullscreen mode

Output

The original size of Image is:  1953.24 KB
The size of compressed image is:  56.89 KB
Enter fullscreen mode Exit fullscreen mode

compress and resize the image using python

Download from the web and compress the image

We can also download an image from the web and compresses it using the Python pillow library.
To download the image from the web we first need to install the Python requests library.

pip install requests
Enter fullscreen mode Exit fullscreen mode
import PIL
from PIL import Image
import requests

img_url = "https://images.pexels.com/photos/60597/dahlia-red-blossom-bloom-60597.jpeg"

response = requests.get(img_url)


#download image 
with open("downloaded.jpg", 'wb') as save_image:
    save_image.write(response.content)

#open the image
with  Image.open('downloaded.jpg') as my_image:

    # the original width and height of the image
    image_height = my_image.height
    image_width = my_image.width

    print("The original size of Image is: ", round(len(my_image.fp.read())/1024,2), "KB")

    #compressed the image
    my_image = my_image.resize((image_width,image_height),PIL.Image.NEAREST)

    #save the image
    my_image.save('compressed.jpg')

    #open the compressed image
    with Image.open('compressed.jpg') as compresed_image:
        print("The size of compressed image is: ", round(len(compresed_image.fp.read())/1024,2), "KB")
Enter fullscreen mode Exit fullscreen mode

Output

The original size of Image is:  706.43 KB
The size of compressed image is:  401.19 KB
Enter fullscreen mode Exit fullscreen mode

download and compress images using python

Compress the uploaded images in Django.

This compress feature of Python with pillow comes very handy with Django when the user upload a high quality image and you wish to compress it.

class UserProfile(models.Model):
    profile_picture = models.ImageField(upload_to='profile_pictures', blank=True, verbose_name='Profile Picture')

def save(self, * args, **kwargs):
        super().save( * args, **kwargs)
        if self.profile_picture:
            img= Image.open(self.profile_picture.path)

            if img.height>1000 or img.width >1000:
                output_size= (500,500)
                img.resize((output_size), PIL.Image.NEAREST)
                img.save(self.profile_picture.path)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)