In this article, we will used the pillow library to compress the image. The pillow library is used to compress the image. The pillow library is a fork of the PIL library. The PIL library is not maintained anymore. So, we will use the pillow library to compress the image.

Installing pillow in python

Pillow is a python library used to compress the image. Pillow is a fork of the PIL library. The PIL library is used to compress the image. The PIL library is not maintained anymore. So, we will use the pillow library to compress the image.

pip install pillow

If you use requirements.txt file to install the dependencies, then add the pillow library to the requirements.txt file.

pip freeze > requirements.txt

   

Compress the image using pillow

from PIL import Image

image = Image.open('image.jpg')
image.save('image_compressed.jpg', optimize=True, quality=50)

Here, image.jpg is the name of the image to be compressed and image_compressed.jpg is the name of the compressed image. The save() function takes three arguments. The first argument is the name of the compressed image. The second argument is the optimize argument. The third argument is the quality argument.

The optimize argument is used to optimize the image. The quality argument is used to set the quality of the image. The quality of the image ranges from 1 to 95.

Optimize parameter is supported by the following image formats: JPEG, PNG, WebP, and TIFF. The quality parameter is supported by the following image formats: JPEG, WebP, and TIFF.

   

Compressing the image from http POST request

from PIL import Image

## ... http POST request

image = Image.open(request.files['image'])
image.save('image_compressed.jpg', optimize=True, quality=50)

   

Client side javascript

In the client side, we will use the FormData object to send the image to the server. The FormData object is used to send the data to the server. Content type of the request will be multipart/form-data.


const image = document.getElementById('image');
const form = document.getElementById('form');

form.addEventListener('submit', (e) => {
    e.preventDefault();
    const formData = new FormData();
    formData.append('image', image.files[0]);
    fetch('/compress', {
        method: 'POST',
        body: formData
    })
    .then(res => res.json())
    .then(data => console.log(data))
    .catch(err => console.log(err));
});

   

Here, image is the id of the input type file. form is the id of the form. formData is the FormData object. formData.append() is used to append the image to the formData object. fetch() is used to send the request to the server. The fetch() function takes two arguments. The first argument is the url of the server. The second argument is the request object. The request object takes two arguments. The first argument is the method of the request. The second argument is the body of the request. The body of the request is the formData object.