How to use Python 3 Pillow on Raspbian Stretch Lite to compress your jpeg image

When you are building a Raspberry Pi camera project, you may want to compress the images captured from the camera to reduce the time to upload your image to a server endpoint. Moreover, when you connect your Raspberry Pi to your iPhone Personal WiFi hotspot, you will want to incur minimal mobile bandwidth charges from demonstrating your Raspberry Pi project in your class.

You may have either:

In this case, you will have the option to use Pillow, a fork of Python Imaging Library, to compress your jpeg image.

Setting up Pillow on your Raspbian Stretch Lite

Before you can use Pillow, you need to setup Pillow dependencies on your Raspbian Stretch Lite. Follow through that tutorial before continuing.

Python 3 code example on using Pillow to compress a jpeg image

After making sure that Pillow can be used in your Python 3 environment on Raspbian Stretch Lite, you can write the codes to compress your jpeg images.

The following is a Python 3 function that takes in a path to an image and compresses the image with 65% quality:

from PIL import Image

def compress_jpeg_image(image_path):
    picture = Image.open(image_path)
    picture.save(image_path, "JPEG",optimize=True,quality=65)

You can then use the function to compress an image that resides on the filesystem of your Raspbian Stretch Lite:

compress_jpeg_image('/home/pi/a_jpeg_image.jpg')

With these Python 3 codes, I can get around 8 to 10 times reduction in the size of the image that my Raspberry Pi camera captures.

About Clivant

Clivant a.k.a Chai Heng enjoys composing software and building systems to serve people. He owns techcoil.com and hopes that whatever he had written and built so far had benefited people. All views expressed belongs to him and are not representative of the company that he works/worked for.