Convert PNG to JPG in Python

We can easily convert PNG images to JPG 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.png")
  • Save the file in JPG format
im.save("file.jpg", "JPEG")

In short, this can be achieved as follows:

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

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 = '.jpg'

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, "JPEG")
    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 (JPG in our case)
target_directory = '.'
target = '.jpg'
  • 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 JPG file
im = Image.open(filename + extension)
im.save(filename + target, "JPEG")
  • 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, "JPEG")
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 PNG images to JPG images in Python. Enjoy.