How to convert PNG images in a directory to JPG using Python

To convert several PNG images to JPG images, the convert command in Linux was not good enough and gave errors. It seems it could not process the large volume of PNG files. Therefore, the image files were converted from PNG to JPG using Python using the following code. Before using the code, Python 3 gave an error as the PIL library is no more separate but a part of the python3-willow package in Linux. Open a terminal window and install it as below.

$ sudo apt-get install python3-willow <enter>

Once this is done, enter and save the below code as png2jpg.py.

# Import Pillow library
from PIL import Image
import os

# Fetch list of all files in the current directory
files = os.listdir(".")

# For each file in the list
for file in files:
	# Convert files that end with .png i.e PNG files
	if file.endswith(".png"):
		# If the file endsWith .png, convert it to JPG
		im = Image.open(file).convert("RGB")
		# Save the file as jpg.
		im.save("./" + file[:-4] + ".jpg")

To run the program, in the terminal window, enter:

$ python3 png2jpg.py <enter>

This will convert all PNG image files to JPG image files in the current folder.

Leave a comment