Optimize images with python

Nelson Hernández
1 min readSep 5, 2020

In this example we will create a function to reduce the weight of our images

1) Creation of virtual environment

In this case I decided to use virtualenv but you can use pipenv if you like.

virtualenv venv
source ./venv/bin/activate

2) Installation of dependencies

pip install Pillow bson

3) Create function

ObjectId() : we get a unique id for the image

typing : We declare the type of data that our function will carry

from PIL import Image
import typing
from bson.objectid import ObjectId
def resize_image(filename=str, extension=str):
image = Image.open(filename)
image.thumbnail(image.size)
image.save(f'{ObjectId()}.{extension}', optimize=True,
quality=30)
print('
saved')

4) Create Pool de Threads

We will create two threads to improve the performance of our app

from PIL import Image
import logging
import typing
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor
import time
def resize_image(filename=str, extension=str):
image = Image.open(filename)
image.thumbnail(image.size)
image.save(f'{ObjectId()}.{extension}', optimize=True,
quality=30)
print('
saved')
if __name__ == "__main__":
executor = ThreadPoolExecutor(max_workers=2)
start = time.time()
executor.submit(resize_image, "flask-twitter.png", "png" )
executor.submit(resize_image, "flask-twitter.png", "png" )
print(f'tarea terminada en: {time.time() - start}')

--

--