# Convert JPG to PNG in Python

Strongly suggest you to get your own portfolio site and show us :)

We can easily convert JPG images to PNG images in Python using the library "Python Image Library (PIL)" (also known as pillow).

There are 4 steps to the process:

• Install PIL library
pip install pillow --user

• Import the PIL library
from PIL import Image

• Open the file that needs to be converted
im = Image.open("file.jpg")

• Save the file in PNG format
im.save("file.png")


In short, this can be achieved as follows:

from PIL import Image
im = Image.open("file.jpg")
im.save("file.png")


# Script to convert all JPG images to PNG

Quick Python script to convert all files in current directory to "png" images:

from PIL import Image
from os import listdir
from os.path import splitext

target_directory = '.'
target = '.png'

for file in listdir(target_directory):
filename, extension = splitext(file)
try:
if extension not in ['.py', target]:
im = Image.open(filename + extension)
im.save(filename + target)
except OSError:
print('Cannot convert %s' % file)


Save the above code in a file named "opengenus.py" and run it as follows:

python opengenus.py


Once the conversion is done, you may delete the old JPG files using the following command:

rm *.jpg


In case, you do not want the new PNG files, you can delete them using the following command:

rm *.png


Note: The above command will delete all PNG files in the current directory. To delete the newly generated file, name the new files in a specific format like "new[filename].png" and then, we can delete the new files as:

rm new*.png


In the script, we do the following:

• Specify the directory to check (current directory in our case) and specify the final file extension (PNG in our case)
target_directory = '.'
target = '.png'

• Get the list of files in the current directory
listdir(target_directory)

• Traverse through all files
for file in listdir(target_directory)

• Get the filename and extension of the current file
filename, extension = splitext(file)

• Open image and convert to PNG file
im = Image.open(filename + extension)
im.save(filename + target)

• Error handling in the process of saving PNG image
try:
if extension not in ['.py', target]:
im = Image.open(filename + extension)
im.save(filename + target)
except OSError:
print('Cannot convert %s' % file)


# Conclusion

JPG and PNG are two different image formats (differing in how images are represented internally) and often, conversion between the two formats are needed. In this article, we demonstrated how easy it is to convert JPG images to PNG images in Python. Enjoy.