[Python] Jpeg to Png Convertor

Nikhil Narayanan
2 min readApr 10, 2020

Today, we will discuss about how to convert jpg image to a png image. This sounds silly, while hearing for the first, but it is rather really useful when we are trying to convert a large set of images.

I am going to introduce you to a Python library called PIL (Python Image Library). This is one of the most widely used library for working with images.

PIL is really popular about python till version 2.x, for python version 3.x, developers have made a fork from this official PIL repository and created a new one called Pillow.

With Pillow, we can do many interesting things with images in Python. Here I am going to discuss about converting .jpg images to .png. This is a small program written in Python 3, which helps to convert all .jpg files inside a particular folder to .png images — by creating a separate directory and then adding the .png files in it.

This code can be run like,

jpg2png-convertor.py pokemon_jpg pokemon_png

Here pokemon_jpg is the folder containing all jpg files and pokemon_png is the folder where I want to put all png files after converting.

Before executing this code, make sure you have Pillow module installed, if not, you can install the module like this,

pip install Pillow

Installation document can be found here

In above code, I have used sys.argv to get the user arguments specifying which is the source folder and to which folder I need to create the .png files to. We can use argparse also to gather the same input from user.

Also,, instead of using regular expression, we can use os.path.splitext() to make this work the same way. So the program will look like,

jpg2png-convertor1.py -s pokemon_jpg -d pokemon_png

This one make more meaningful entries. Sounds good. we have discussed two versions of the same program, you can follow as per your wish.

We can do many move conversion using Pillow module, like from .png back to .jpg and many move. Using the provided code above and with little reading on the Pillow Image module, we can do so many amazing thing using images

Thanks for reading. Have a wonderful day ahead..!!

--

--

Nikhil Narayanan

DevOps Engineer | Python Developer | Machine Learning | Artificial intelligence Enthusiast