Python PIL Image.open() method

Python PIL Image.open() Method

PIL is the Python Imaging Library, which provides image editing capabilities for the Python interpreter. The Image module provides a class of the same name to represent a PIL Image. The module also provides factory functions for loading images from files and creating new images.

PIL.Image.open() Opens and identifies the given image file.

This is a lazy operation; the function identifies the file, but the file remains open; the actual image data is not read from the file until you attempt to process the data (or call the load() method). See new().

Syntax: PIL.Image.open(fp, mode='r')

Parameters:

fp – A filename (string), a pathlib.Path object, or a file object. The file object must implement the read(), seek(), and tell() methods and be opened in binary mode.
mode – The mode. If given, this parameter must be “r”.

Return Type: An image object.
Raises: IOError – If the file cannot be found, or the image cannot be opened and recognized.

Image used:
Python PIL Image.open() method

# Imports PIL module 
from PIL import Image
  
# open method used to open image files with different extensions
im = Image.open(r"C:UsersSystem-PcDesktopybear.jpg") 
  
# This method will display the image in any image viewer 
im.show() 

Output: The .JPG extension image is opened.

Python PIL Image.open() Method

Another example: Here we use a file with the .PNG extension.

Images used:
Python PIL Image.open() method

# Imports PIL module 
from PIL import Image
  
# open method used to open image files with different extensions
im = Image.open(r"C:UsersSystem-PcDesktoplion.png") 
  
# This method will display the image in any image viewer 
im.show() 

Output: .PNG extension image opened.
Python PIL Image.open() method

Leave a Reply

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