How to Convert Image File Format Using Python

Python is known for its versatility. You can create real utility tools in Python that can simplify and automate certain tasks.


Learn how to create an image type converter with just a few simple lines of Python code. Whether it’s a single image file or all files in a directory, you can easily convert between different formats.


Install required libraries

You need to install the Pillow Python library to build an image type converter in Python. This library enhances the image processing capabilities of your Python interpreter. You can create a general image processing tool using several modules from this library. Some of the most useful are Image, Image file, Image filterand ImageStat mods.

Run the following command in the terminal to install the Pillow Python library:

pip install pillow

Once Pillow is installed on your system, you are ready to work with images.

Loading and Viewing Image Properties

First you need to import the Image modulus of the DIPs library to configure the code. Then you have to use the Image.open() method to load the image and assign it to a variable. Once the image is loaded, you can view it using the To display() method.

The image format converter code is available in a GitHub repository and you can use it for free under the MIT license.

from PIL import Image
image = Image.open('sample-image.jpg')
image.show()

The image you passed as a parameter to the open() The method will open after executing the code. This is a good first step, as an integrity check, to make sure you have successfully installed the library on your system.

The Image module provides several other properties that you can use to get more information about the image.


from PIL import Image


image = Image.open('sample-image.jpg')


print("Filename: ", image.filename)


print("Format: ", image.format)


print("Mode: ", image.mode)


print("Size: ", image.size)


print("Width: ", image.width)


print("Height: ", image.height)


image.close()

You should see meaningful data with no errors:

How to Convert Image Format Using Python

You can simply convert the file format of an image using the to register() method. You just have to pass the new file name and the extension as a parameter of the to register() method. The to register() will automatically identify the extension you passed and then save the image in the identified format. But before using the to register() you may need to specify the mode of the image (RGB, RGBA, CMYK, HSV, etc.).

According to the official pillow documentation, the mode of an image is a string that defines the type and depth of a pixel in the image. The Pillow Library supports 11 modes, including the following standard modes:

RGB (3×8 bit pixels, true color)

RGBA (4×8 bit pixels, true color with transparency mask)

CMYK (4×8 bit pixels, color separation)

HSV (3×8 bit pixels, hue, saturation, value color space)

How to convert a PNG image to JPG and JPG to PNG

You have to pass the chain filename.jpg as a parameter of the to register() method to convert image files in any format (PNG, GIF, BMP, TIFF, etc.) to JPG format. Also, you must provide the mode of the image. The following code converts an image from PNG format to JPG format:


from PIL import Image


image = Image.open('sample-png-image.png')


image = image.convert('RGB')


image.save("converted-jpg-image.jpg")
print("Image successfully converted!"

You will lose all transparency in an image if you convert it to JPG format. If you try to preserve transparency using the RGBA mode, Python will return an error.

You can convert an image in any format to PNG using the to register() method. Just pass the PNG image as a parameter to the to register() method. The following code converts an image from JPG format to PNG format:


from PIL import Image


image = Image.open('sample-jpg-image.jpg')


image.save("converted-png-image.png")
print("Image successfully converted!")

Converting an image to PNG preserves all transparency. For example, if you convert a transparent GIF image to a PNG image, the result will always be a transparent image.

How to convert an image to any other format using Python

Similar to the steps above, you can convert an image in any format to any other format using the to register() method. You just need to provide the correct image extension (.webp, .png, .bmp, etc.) to the to register() method. For example, the following code converts an image from PNG format to WebP format:


from PIL import Image


image = Image.open('sample-transparent-png-image.png')


image.save("converted-webp-image.webp")
print("Image successfully converted!")

Error handling for missing image files

If the code is unable to find the input image, it will generate an error. You can handle this using the FileNotFoundError Python exception.


from PIL import Image

try:
image = Image.open('wrong-filename.jpg')


image.save("converted-png-image.png")
print("Image successfully converted!")

except FileNotFoundError:
print("Couldn't find the provided image")

Converting all images in a directory to a different format

If there are multiple image files in a directory that you want to convert to a different format, you can easily do this with just a few lines of code in Python. You need to import the overall library to browse the files in the current directory or in a given folder. The following code converts all JPG images in the current directory to PNG format:

from PIL import Image
import glob

for file in glob.glob("*.jpg"):
image = Image.open(file)
image.save(file.replace("jpg", "png"))

If you want to convert another set of files, change the string parameter you pass to the glob() method.

Build a GUI using Python

Python libraries like Pillow make it easy to develop tools to process images in Python. You can perform tasks quickly with a command-line interface, but a GUI is essential to create a user-friendly experience. You can build more specialized GUI applications using Python frameworks such as Tkinter and wxPython.