Python Image Library: Convert Type and Quality of Image
JPEG – JPEG files were designed to make detailed photographic images as small as possible by removing information that the human eye won’t notice. So the size of the image is much smaller compared to that of PNG. However, JPEG files cannot store the alpha transparency information of the image. So, if transparency information isn’t required, JPEG is the most scalable solution.
PNG – PNG is a great format that combines Lossless encoding with Direct Color (thousands of colours, just like JPEG). It also supports alpha transparency. A photograph saved as a PNG will likely be at least 5 times larger than an equivalent JPEG image, offering a little improvement in visible quality. So, if file size isn’t a problem and you want the best possible quality, then PNG is the way to go.
In our case, most images will be uploaded to our website. So, the smaller the better. We therefore store most large image files in JPEG format by converting PNG to JPEG using PIL (Python Image Library).
PNG to JPEG Conversion
The Python Imaging Library, or PIL in short, is one of the core libraries for image manipulation in Python. Unfortunately, its development has stagnated, with its last release in 2009.
Luckily for you, there’s an actively-developed fork of PIL called Pillow – it’s easier to install, runs on all operating systems, and supports Python 3.
The most important class in the Python Imaging Library is the
Image class, defined in the module with the same name. You can create instances of this class in several ways; either by loading images from files, processing other images, or creating images from scratch.
While converting from PNG to JPEG, we create a new image file in JPEG format, read the PNG image, then paste the read image to the newly created blank JPEG image. Then the JPEG image file is saved. This is the basic idea behind conversion from PNG to JPEG.
As you can see, when saving a JPEG image, we can specify the quality it is to be saved in. So if we want, we can take the quality input for conversion from the admin, and then decide the quality while changing from PNG to JPEG.
This is an important feature because most large images, such as backgrounds or header backgrounds, are already of a huge size. Manipulating such images and saving the files in PNG format only increases the size further.. So, considering ease of page design, you may find it more convenient to store such images in JPEG format.This will make your website more scalable, and make image upload faster.
This post was originally posted by the author on fossasia. This version has been edited for clarity and may appear different from the original post.