VMware ESXi and vSphere Cluster Management
Load an Image with Pillow
Learn how to open local JPEG, PNG, and other image files with Pillow, display them with show(), inspect metadata, handle paths, and troubleshoot loading errors.
Pillow is a Python imaging library for opening, inspecting, transforming, and saving image files. It is commonly used through the PIL package namespace. This lesson shows how to load a local image and display it for a quick visual check.
Prerequisites and installation
You should know how to run a Python script or interactive session, use basic imports and variables, and work with files and folders. If Pillow is not installed, install it with:
python -m pip install Pillow
Pillow's image-loading API
Pillow provides the PIL.Image module for opening and manipulating image files. Import the module with:
from PIL import Image
Image in this statement refers to the imported module. It is different from an image object. An image object is the in-memory object returned after a file is opened. You use that object to inspect properties, display the image, transform it, or save it.
Open a local image file
The standard function for opening an image from disk is Image.open(). It accepts a filename, a relative path, an absolute path, or a pathlib.Path object, and returns a Pillow image object.
from PIL import Image
img = Image.open("handsome.jpg")
Here, Image.open() is the function, while img is the image object returned by that function. The file named handsome.jpg must really exist in a location that the program can access.
Minimal working example: open and display a JPEG
This is the smallest complete workflow for loading a local JPEG and checking it visually:
from PIL import Image
img = Image.open("handsome.jpg")
img.show()
Replace handsome.jpg with the name of an actual image file available to your program. The filename does not have to be that exact name; it is only an example.
Display the loaded image with show()
show() is a method on the image object. It asks the operating system to open the image in its associated or default image viewer.
img.show()
This method is primarily useful for quick local inspection and debugging. It is not usually the best way to build a graphical user interface or display images in a web application.
Depending on the platform and Pillow's display workflow, the viewer may open a temporary copy of the image. Therefore, the viewer window title or displayed filename might not match the original source filename. Judge the result by the visible image and the image metadata, not only by the viewer's title.
File locations and paths
A bare filename such as handsome.jpg is resolved relative to Python's current working directory. The current working directory is the directory from which Python resolves relative file paths. It may not be the same directory as the script file.
from PIL import Image
img = Image.open("images/photo.png")
This is a relative path. Python looks for an images subfolder inside the current working directory.
An absolute path gives the complete filesystem location and does not depend on the current working directory. For example, a Windows path might be written as:
img = Image.open(r"C:\Users\Alex\Pictures\photo.png")
On a Unix-like system, an absolute path might look like:
img = Image.open("/home/alex/Pictures/photo.png")
Using pathlib.Path is an optional, portable way to construct paths:
from pathlib import Path
from PIL import Image
image_path = Path("images") / "photo.png"
img = Image.open(image_path)
| Path form | Example | When to use |
|---|---|---|
| Filename in the current working directory | "handsome.jpg" | When the image is directly in the directory from which Python resolves relative paths. |
| Relative path to a project subfolder | "images/photo.png" | When the image is stored in a folder below the current working directory. |
| Absolute filesystem path | "/home/alex/Pictures/photo.png" | When the image is elsewhere and you need to specify its complete location. |
pathlib.Path object | Path("images") / "photo.png" | When you want platform-aware path construction and readable path operations. |
Supported image formats
Pillow can identify and open common formats such as JPEG, PNG, GIF, BMP, TIFF, and WebP when the relevant format support is available in the Pillow installation.
Opening a file depends on its actual contents and Pillow's available format support, not only on its filename extension. A file named photo.jpg may contain invalid data, or it may not actually be a JPEG. Conversely, a correctly encoded image may sometimes have an unusual or missing extension.
Verify a loaded image
After opening an image, inspect its basic attributes to confirm that the expected file was found and recognized:
from PIL import Image
img = Image.open("handsome.jpg")
print("Format:", img.format)
print("Size:", img.size)
print("Mode:", img.mode)
print("Filename:", img.filename)
These values provide useful information:
format: the detected file format, such asJPEGorPNG.size: a tuple containing the image width and height in pixels, such as(1920, 1080).mode: the pixel representation, such asRGB,RGBA, grayscaleL, or palette-basedP.filename: the source location recorded by Pillow when the image was opened from a file.
| Property or method | What it reveals | Example use |
|---|---|---|
format | The detected image file format. | print(img.format) |
size | The width and height in pixels. | print(img.size) |
mode | The pixel and color representation. | print(img.mode) |
filename | The source location associated with the opened file. | print(img.filename) |
load() | Forces the image pixel data to be read. | img.load() |
show() | Opens the image in an operating-system image viewer. | img.show() |
Pillow may read image metadata first and defer reading pixel data until it is needed. Calling load() explicitly forces the pixel data to be read:
from PIL import Image
img = Image.open("handsome.jpg")
img.load()
print(img.size)
Explicit loading can be useful when you need to ensure that all pixel data has been read while the source file is still available.
Lazy loading and resource management
Lazy loading means that Pillow can identify the image and read metadata without immediately reading every pixel. This can make opening a file efficient, but it also means that some pixel operations may still depend on the source file being available.
When an image is needed only inside a short block, use a context manager. It ensures that the file resource is closed when the block ends:
from PIL import Image
with Image.open("images/photo.png") as image:
print("Format:", image.format)
print("Size:", image.size)
print("Mode:", image.mode)
If the image must remain usable after the context manager ends, make a copy inside the block. The copy detaches the image data from the file resource:
from PIL import Image
with Image.open("images/photo.png") as source:
img = source.copy()
img.show()
Another option is to call load() before leaving the block when appropriate. A copy is the clearer choice when you need an independent image object for later processing.
Common image-loading errors
| Symptom or exception | Likely cause | Resolution |
|---|---|---|
FileNotFoundError | The filename is wrong, the capitalization differs, or Python is using an unexpected current working directory. | Check the filename and path, inspect the current working directory, and use a verified relative or absolute path. |
UnidentifiedImageError | The file is not a valid supported image, has misleading contents or an extension, or is corrupted. | Open it in another image application, verify that it is complete and really an image, then use a valid file or convert it to a supported format. |
PermissionError | The process does not have permission to read the file or one of its parent folders. | Check filesystem permissions and access the file from a location the process can read. |
| An error caused by damaged or incomplete image data | The file was truncated, incompletely downloaded, or corrupted during copying. | Obtain the source file again or re-export it as a valid image before opening it. |
Diagnose a missing file
If Python cannot find the image, check the spelling and capitalization first. Then inspect the current working directory:
from pathlib import Path
print(Path.cwd())
Place the image in the expected folder or update the argument passed to Image.open(). A verified relative path or an absolute path can help distinguish a path problem from an image-format problem.
Diagnose an unidentified image
UnidentifiedImageError indicates that Pillow could not recognize the file as a supported image. The file may be corrupted, have misleading contents, or even be an HTML error page saved with an image extension. Try opening it with another image application and confirm that a download or file copy completed successfully.
from PIL import Image
from PIL import UnidentifiedImageError
try:
img = Image.open("handsome.jpg")
except UnidentifiedImageError:
print("The file is not a valid supported image.")
Complete example with metadata and display
from PIL import Image
image_path = "handsome.jpg"
img = Image.open(image_path)
print("Format:", img.format)
print("Size:", img.size)
print("Mode:", img.mode)
print("Filename:", img.filename)
img.show()
The workflow is: identify the file path, call Image.open(), receive a Pillow image object, inspect its properties, and optionally call show() for a quick local visual check.
Key exam and practice notes
- Use
from PIL import Imageto import Pillow's image module. - Use
Image.open(path)to open an image and return a Pillow image object. - A bare filename is resolved from the current working directory.
- Use a relative path for a project subfolder and an absolute path for a complete filesystem location.
- Use
format,size,mode, andfilenameto verify what was loaded. show()is intended for quick local inspection and may use a temporary file.- Use a context manager for short-lived file access, and call
copy()before leaving the block if the image must remain usable afterward. FileNotFoundErrorusually indicates a path problem;UnidentifiedImageErrorusually indicates invalid, unsupported, or corrupted image data.