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.
    Image.save(fp, format=None)
  3. fp: the saved path of the picture, including the name of the picture, and the value is in string format.
  4. format: specify the format of the image, this parameter is optional.
  5. In the below example, I use the pillow module’s Image class’s save() method to convert the source .tif image file to a .png image file.
    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)
  3. The following errors will occur when you use the save() method directly.
    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 <module>
        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 {im.mode} as JPEG") from e
    OSError: cannot write mode RGBA as JPEG
  4. The error is caused by the inconsistency between PNG and JPG image modes.
  5. PNG is a 4-channel RGBA mode that is red, green, blue, and Alpha transparent color and JPG is a three-channel RGB mode.
  6. Therefore, if you want to achieve the conversion of image format, you need to convert PNG into three-channel RGB mode.
  7. The Image class provides the convert() method to convert Image modes. This function provides multiple arguments, such as mode, matrix, dither, and so on.
  8. The most critical parameter is the mode, and other parameters need not be concerned. The below is the method syntax.
    convert(mode,parms**)
  9. mode: refers to the image mode to be converted to.
  10. params: other optional parameters.
  11. So you can change the source code to the below to avoid the error, just need to add one line convert code to convert the PNG image mode from RGBA to RGB.
    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

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

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