Originally posted on makeuseof.
Go from PNG to JPEG and back again, with ease, using this powerful library.
Python is known for its versatility. You can create real-world utility tools in Python that can simplify and automate certain tasks.
Learn how to build 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.
Installing Required Libraries
You need to install the Pillow Python library to build an image-type converter in Python. This library advances the image-processing capabilities of your Python interpreter. You can create a general image processing tool using several modules of this library. Some of the most useful are the Image, ImageFile, ImageFilter, and ImageStat modules.
Run the following command in the terminal to install the Pillow Python library:
pip install pillow
Once you have Pillow installed on your system, you are ready to work with images.
Loading and Displaying Properties of an Image
First you need to import the Image 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. Once you have loaded the image, you can display it using the 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 that you passed as a parameter to the open() method will open up after you execute 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.
# Importing library
from PIL import Image
# Loading the image
image = Image.open('sample-image.jpg')
# Prints the name of the file
print("Filename: ", image.filename)
# Prints the format of the file
# Eg- PNG, JPG, GIF, etc.
print("Format: ", image.format)
# Prints the mode of the file
# Eg- RGB, RFBA, CMYK, etc.
print("Mode: ", image.mode)
# Prints the size as a width and height tuple (in pixels)
print("Size: ", image.size)
# Prints the width of the image (in pixels)
print("Width: ", image.width)
# Prints the height of the image (in pixels)
print("Height: ", image.height)
# Closing the image
image.close()
You should see some meaningful data with no errors:
How to Convert Image Format Using Python
You can simply convert the file format of an image using the save() method. You just need to pass the new filename and extension as a parameter to the save() method. The save() method will automatically identify the extension that you passed and then save the image in the identified format. But before using the save() method, 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 an Image From PNG to JPG and JPG to PNG
You need to pass the string filename.jpg as a parameter to the save() method to convert image files in any format (PNG, GIF, BMP, TIFF, etc.) to JPG format. Also, you need to provide the mode of the image. The following code converts an image from PNG format to JPG format:
# Importing Library
from PIL import Image
# Loading the image
image = Image.open('sample-png-image.png')
# Specifying the RGB mode to the image
image = image.convert('RGB')
# Converting an image from PNG to JPG format
image.save("converted-jpg-image.jpg")
print("Image successfully converted!"
You’ll lose any transparency in an image if you convert it to JPG format. If you try to preserve the transparency using the RGBA mode, Python will throw an error.
You can convert an image in any format to PNG format using the save() method. You just need to pass the PNG image as a parameter to the save() method. The following code converts an image from JPG format to PNG format:
# Importing Library
from PIL import Image
# Loading the image
image = Image.open('sample-jpg-image.jpg')
# Converting image from JPG to PNG format
image.save("converted-png-image.png")
print("Image successfully converted!")
Converting an image to PNG preserves any transparency. 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 Any Other Format Using Python
Similar to the steps above, you can convert an image in any format to any other format using the save() method. You just need to provide the correct image extension (.webp, .png, .bmp, etc.) to the save() method. For example, the following code converts an image from PNG to WebP format:
# Importing Library
from PIL import Image
# Loading the image
image = Image.open('sample-transparent-png-image.png')
# Converting an image from PNG to WEBP format
image.save("converted-webp-image.webp")
print("Image successfully converted!")
Error Handling for Missing Image Files
In case the code is not able to find the input image, it will throw an error. You can handle this using the FileNotFoundError Python exception.
# Importing Library
from PIL import Image
try:
# Loading the image
image = Image.open('wrong-filename.jpg')
# Converting image from JPG to PNG format
image.save("converted-png-image.png")
print("Image successfully converted!")
except FileNotFoundError:
print("Couldn't find the provided image")
Converting All the Images in a Directory to a Different Format
If there are several image files in a directory, that you want to convert to a different format, you can easily do so with just a few lines of code in Python. You need to import the glob library to iterate through the files in the current directory or inside a given folder. The following code converts all the 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 the glob() method.
Build a GUI Using Python
Python libraries like Pillow make it easy to develop tools to deal with 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 like Tkinter and wxPython.
Source: makeuseof