Image Conversion (JPG ⇄ PNG/JPG ⇄ WEBP) with Python

Ajeet Verma
3 min readDec 15, 2019

--

test.png

Here we are going to use PIL(Python Imaging Library) or pillow library which is widely used for image processing in python and 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.

To load an image from a file, use the open() function in the Image module:

Image Conversion

Image.convert() returns a converted copy of this image. For the “P” mode, this method translates pixels through the palette. If mode is omitted, a mode is chosen so that all information in the image and the palette can be represented without a palette.

The current version supports all possible conversions between “L”, “RGB” and “CMYK.” The matrix argument only supports “L” and “RGB”.

save(fp, format) takes two input parameter, first file path(fp) to save the converted file and second the file format to convert into.

JPG to PNG:

PNG to JPG:

JPG to WEBP:

WEBP to JPG:

PNG to WEBP:

WEBP to PNG:

References: PIL documentat, Image, Arrows

Hope this blog will be useful and feel free to ask questions and if you like it, please let me know in the comment section below. Happy :) reading!

--

--