Compress Images size with Python
Tags: python, programming, pillow, imagecompression
Published: 2022-08-27 07:41:29

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.
```bash
pip install pillow
```

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

```python
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")

```
**Output**
```bash
The original size of Image is:  1953.24 KB
The size of compressed image is:  1547.01 KB
```

![compress the images using python](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/704z762cd5fmiukabddl.jpg)
**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](https://pillow.readthedocs.io/en/stable/handbook/concepts.html#concept-filters). 
4. At last save the compressed image using the save() method.


> **Note**: I used the 
> ```python
> 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.
```python
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")
```
**Output**
```bash
The original size of Image is:  1953.24 KB
The size of compressed image is:  56.89 KB
```

![compress and resize the image using python](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ptjvly7c2gmvat5a1la6.jpg)

###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.
```bash
pip install requests
```

```python
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")
```
**Output**
```bash
The original size of Image is:  706.43 KB
The size of compressed image is:  401.19 KB
```

![download and compress images using python](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hfpuywfxp4fwkbae5f66.jpg)


##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.
```python
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)
```