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:
- Setup Raspbian Stretch Lite on Raspberry Pi 3 to run Python 3 applications, or
- Setup Raspbian Stretch Lite on Raspberry Pi Zero W to run Python 3 applications.
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:
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.