5 Different ways to compress image using python script.

Using high quality image make our website slow and give an unpleasant experience to the user. SO, we can use python script to compress the image quality. Here some method to achieve this.

1. PIL

You can use the Python Imaging Library (PIL) to compress an image without losing quality or resizing it. Here is an example script that opens an image and saves it to a new file with a lower quality setting:

from PIL import Image

# Open the image
im = Image.open("original.jpg")

# Save the image with a lower quality setting
im.save("compressed.jpg", optimize=True, quality=95)

You can adjust the quality setting to control the level of compression. Higher quality settings will result in less compression and a bigger file size, but the image will retain its quality. The optimize parameter set to True will optimize the image file. This will reduce file size without loss of image quality.

2. OpenCv

You can also use other libraries like opencv which allow you to compress image without lossing quality and resizing.

import cv2

# Open the image
im = cv2.imread("original.jpg")

# Compress the image
encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 95]
result, encoded_img = cv2.imencode('.jpg', im, encode_param)

# Save the compressed image
cv2.imwrite("compressed.jpg", encoded_img)

You can adjust the quality setting to control the level of compression. Higher quality settings will result in less compression and a bigger file size, but the image will retain its quality.

3. Shutil

You can use the shutil library in python to compress an image without losing quality and resizing. Here is an example script that uses shutil to compress an image file to a smaller size without any loss in quality:

import shutil

# Open the image
with open("original.jpg", "rb") as f_in:
    # Compress the image
    with open("compressed.jpg", "wb") as f_out:
        shutil.copyfileobj(f_in, f_out, length=131072)

The length parameter in shutil.copyfileobj controls the buffer size for the compressed image file, which directly affects the compression level. By default, it is set to a high value (typically around 2MB) to minimize the effect on performance.

4. Torch

Alternatively, you can use libraries like PyTorch or TensorFlow to compress the image file with high-quality.

import torch

img = torch.randn(3, 512, 512)
torch.save(img, "original.pt")
torch.save(img, "compressed.pt", _compression_level=9)

The _compression_level parameter in torch.save controls the compression level, where 9 is the highest level of compression.

5. Third party API

Additionally, you can use third party libraries like tinyPNG or tinyJPG that provide compression without losing quality. You can use their API to compress the image and then download the compressed image.

import requests

api_key = 'your_api_key'

response = requests.post(
    'https://api.tinypng.com/shrink',
    headers={
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': 'Basic ' + api_key
    },
    data={
        'input': '@/path/to/your_image.png'
    }
)

if response.status_code == 201:
    with open('compressed_image.png', 'wb') as f:
        f.write(response.content)
else:
    print("Compression failed")

Please note that you need to signup on the website and get the API key to use this service.

Leave a Reply