How to Convert Image File Format Using Python

Python is known for its versatility. You can create handy utilities in Python that can simplify and automate specific 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 those pillow Python library to create an image type converter in Python. This library extends the image processing capabilities of your Python interpreter. With several modules of this library you can create a general image processing tool. Some of the most useful are these picture, image file, image filterand ImageStat modules.

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

pip install pillow

Once Pillow is installed on your system, you can work with images.

Load and display properties of an image

First you need to import the picture module from the PIL library to set up the code. Next you need to use the image.open() Method to load the image and assign it to a variable. After loading the image, you can view it with Show() Method.

The image format converter code is available in a GitHub repository and is free for you to use 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() method is opened after you run the code. This is a good first step as a sanity check to ensure 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 some meaningful data with no errors:

How to convert image format using Python

You can easily convert the file format of an image with save up() Method. You just have to pass the new one filename and extension as a parameter for the save up() Method. That save up() method automatically detects the extension you passed and then saves the image in the identified format. But before you use them save up() method, you may need to specify the mode of the image (RGB, RGBA, CMYK, HSV, etc.).

According to the official Pillow documentation, an image’s mode is a string that defines the type and depth of a pixel in the image. The pillow library supports 11 modes including the following default 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 an image from PNG to JPG and JPG to PNG

You must pass the string filename.jpg as a parameter for the save up() Method to convert image files of any format (PNG, GIF, BMP, TIFF, etc.) to JPG format. You must also specify 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 lose all transparency in an image when you convert it to JPG format. If you try the transparency with the RGBA mode, Python will throw an error.

You can convert an image of any format to PNG format using save up() Method. You just need to pass the PNG image as a parameter to the save up() 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!")

When converting an image to PNG, all transparency is preserved. For example, if you convert a transparent GIF image to a PNG image, the result will still be a transparent image.

How to convert an image to another format using Python

Similar to the steps above, you can convert an image of any format to any other format using save up() Method. You just need to provide the correct image extension (.webp, .png, .bmp, etc.) for the save up() Method. For example, the following code converts an image from PNG 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 cannot find the input image, an error is thrown. You can handle this with 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")

Convert all images in a directory to another format

If you have multiple image files in a directory that you want to convert to another format, you can easily do it with just a few lines of code in Python. You have to import them Bullet Library to iterate through the files in the current directory or in a specific 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 a different set of files, change the string parameter you pass to global() Method.

Build a GUI with Python

Python libraries like Pillow make it easy to develop tools for handling 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 create more specialized GUI applications using Python frameworks such as Tkinter and wxPython.

Leave a Reply

Your email address will not be published. Required fields are marked *