There might be a time when we have a folder containing images in jpg format and we want to convert all the images in png.
Doing this manually would consume a lot of time. In this article I have written how this can be done in a single command using few lines of python script.
Png formats are considered better while developing websites. Png has an advantage over jpg that there is no loss in quality, each time it is opened and saved again.
Python Module
Firstly we need a python module called Pillow which is one of the most important modules for image processing in python.
Pillow is built on top of PIL (Python Image Library). This library provides extensive file format support. It was designed for fast access to data stored in a few basic pixel formats.
You can explore the module more by visiting Pillow documentation
Before using this module we need to install it. For using pip3
it is important to have python3 in your system.
pip3 install Pillow
Code
from PIL import Image
import sys
import os
# grab the arguments
image_folder = sys.argv[1]
output_folder = sys.argv[2]
#check if folder exists, if not create it
if not os.path.exists(output_folder):
os.makedirs(output_folder)
#loop through the folder, convert jpg to png, save it to new folder
for filename in os.listdir(image_folder):
img = Image.open(f'{image_folder}{filename}')
# to remove the file extension from filename
filename = os.path.splitext(filename)[0]
img.save(f'{output_folder}{filename}.png' , 'png')
Execution
Execute the above python script from terminal.
python3 filename.py image_folder/ new_folder/
Note: For Windows change /
to \
as followed for path specification.
After execution there would be a new folder created with the images in PNG extension.
Before You Leave
To get the code and image folder refer to my GitHub repo JPG2PNGConverter