Get Image Size, Resolution, and Layers in GIMP Python
This article explains how to programmatically inspect image properties in GIMP using Python-Fu. You will learn how to access the active image object and extract its dimensions in pixels, its horizontal and vertical resolution (DPI), and its total number of layers directly via GIMP's integrated Python console or standalone batch scripts.
Accessing the GIMP Python Console
To interactively test Python commands in GIMP, open the Python-Fu
console by navigating to Filters > Python-Fu >
Console. This environment provides interactive access to the
gimp module and GIMP's Procedural Database (PDB).
Inspecting Image Attributes
When working with an open image, you first obtain a reference to the
target image object. In the interactive console,
gimp.image_list() returns a list of all currently open
images.
Once you have the image object, you can access dimensions, resolution, and layers through the following properties:
- Dimensions: Accessed using the
.widthand.heightattributes, returning integer values representing the image size in pixels. - Resolution: Accessed using the
.resolutionattribute, which returns a tuple of floating-point values representing the horizontal and vertical resolution in dots per inch (DPI):(x_resolution, y_resolution). - Layer Count: The
.layersattribute contains a list of all top-level layers. Using Python's standardlen()function on this attribute yields the layer count.
Python Code Example
Run the following code block in the Python-Fu console to query these properties for the currently selected image:
# Select the most recently opened or active image
image = gimp.image_list()[0]
# 1. Query Dimensions (Width and Height in pixels)
width = image.width
height = image.height
# 2. Query Resolution (X and Y in DPI)
x_res, y_res = image.resolution
# 3. Query Layer Count
layer_count = len(image.layers)
# Output the results
print("Width: {} px".format(width))
print("Height: {} px".format(height))
print("Resolution: {} x {} DPI".format(x_res, y_res))
print("Layer Count: {}".format(layer_count))Handling Nested Layer Groups
The image.layers list includes top-level layer groups as
single items. If your project contains nested layers within groups and
you require an absolute count of every individual layer, traverse the
layer tree recursively:
def count_all_layers(layers):
total = 0
for layer in layers:
total += 1
# Check if the item is a layer group
if hasattr(layer, 'layers'):
total += count_all_layers(layer.layers)
return total
total_layers = count_all_layers(image.layers)
print("Total Layers (including nested): {}".format(total_layers))