Python convert image format

How To Convert Image Format Using Pillow In Python

The Pillow library supports a variety of image formats, and you can read images directly using the open() method regardless of the type of image. At the same time, Pillow makes it easy to convert between image formats. This article will tell you how to convert image formats using python pillow.

1. Pillow Provided Methods To Convert Image Formats.

  1. Pillow provides 2 methods ( save() & convert() ) for us to convert between different image formats.
  2. We will introduce them one by one with examples.

1.1 save().

  1. The save() method is used to save images. When no file format is specified, it will store the image in the default image format. If the image format is specified, the image is stored in the specified format.
  2. The syntax for the save() method is as follows.
from PIL import Image def pillow_save_method_example(): # define the source image file path, the source image file is a .tif file. src_file_path = 'c:\\test.tif' # open the source image file with the pillow image class. image_object = Image.open(src_file_path) # define the target image file path. target_file_path = 'd:\\test-abc.png' # save the source image to the target image file, the target image file is a .png file. image_object.save(target_file_path) if __name__ == '__main__': pillow_save_method_example()

1.2 save() + convert().

  1. Not all image formats can be converted with the save() method.
  2. For example, if you save a PNG format image to a JPG format file like the below source code.
from PIL import Image src_file_path = 'd:\\test.png' target_file_path = 'd:\\test.jpg' image_object = Image.open(src_file_path) image_object.save(target_file_path)
Traceback (most recent call last): File "C:\Users\Jerry\anaconda3\Lib\site-packages\PIL\JpegImagePlugin.py", line 611, in _save rawmode = RAWMODE[im.mode] KeyError: 'RGBA' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "D:\Work\dev2qa.com-example-code\PythonExampleProject\com\dev2qa\example\code_learner_dot_com_example\pillow_example.py", line 94, in pillow_save_method_example() File "D:\Work\dev2qa.com-example-code\PythonExampleProject\com\dev2qa\example\code_learner_dot_com_example\pillow_example.py", line 88, in pillow_save_method_example image_object.save(target_file_path) File "C:\Users\Jerry\anaconda3\Lib\site-packages\PIL\Image.py", line 2151, in save save_handler(self, fp, filename) File "C:\Users\Jerry\anaconda3\Lib\site-packages\PIL\JpegImagePlugin.py", line 613, in _save raise OSError(f"cannot write mode as JPEG") from e OSError: cannot write mode RGBA as JPEG
from PIL import Image # define the source and the target image file path. src_file_path = 'd:\\test.png' target_file_path = 'd:\\test.jpg' # open the source image file. image_object = Image.open(src_file_path) # convert the source file PNG format file mode from RGBA to RGB and return a new Image object. image_object1=image_object.convert('RGB') # save the new mode Image object to the target JPG format file. image_object1.save(target_file_path)

Leave a Comment Cancel Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Читайте также:  Python try except multiple try

Источник

Python PIL | Image.convert() Method

PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images.

Image.convert() Returns a converted copy of this image. For the “P” mode, this method translates pixels through the palette. If mode is omitted, a mode is chosen so that all information in the image and the palette can be represented without a palette.

Syntax: Image.convert(mode=None, matrix=None, dither=None, palette=0, colors=256)

Parameters:
mode – The requested mode. See: Modes.
matrix – An optional conversion matrix. If given, this should be 4- or 12-tuple containing floating point values.
dither – Dithering method, used when converting from mode “RGB” to “P” or from “RGB” or “L” to “1”. Available methods are NONE or FLOYDSTEINBERG (default).
palette – Palette to use when converting from mode “RGB” to “P”. Available palettes are WEB or ADAPTIVE.
colors – Number of colors to use for the ADAPTIVE palette. Defaults to 256.

Returns: An Image object.

Image Used:

Источник

How to Convert Image File Format Using Python

Go from PNG to JPEG and back again, with ease, using this powerful library.

Image format converter using Python

Readers like you help support MUO. When you make a purchase using links on our site, we may earn an affiliate commission. Read More.

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:

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:

Python output showing image metadata from a file

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.

Источник

Оцените статью