get_width()

public function get_width(): int

Description

Returns the width in pixels of the currently loaded image. This method uses PHP's GD library imagesx() function to retrieve the width of the image resource.

Image Must Be Loaded: This method requires an image to be loaded first using load() or upload(). Calling get_width() without a loaded image will throw an Exception with the message "No image is loaded."

Parameters

This method takes no parameters.

Return Value

Type Description
int The width of the loaded image in pixels.

Example #1

The code sample below demonstrates the most basic use of get_width().

Common Use Cases: The get_width() method is typically used to determine aspect ratios, validate image dimensions, calculate resize operations, or make decisions about how to process an image based on its dimensions.

Example #2

The example above shows how to validate image width before processing.

Minimum Dimension Validation: Use get_width() and get_height() to enforce minimum dimension requirements. Upload to a temporary location first, validate dimensions, then move to permanent storage only if valid. This prevents poor-quality images from entering your system.

Example #3

The example above demonstrates using get_width() to determine the optimal resize strategy.

Responsive Image Generation: Check the source width with get_width() before creating responsive sizes. Only generate smaller versions if the source is actually larger than the target. This prevents unnecessary upscaling and maintains image quality.

Example #4

The example above shows using get_width() to calculate proportional crop dimensions.

Aspect Ratio Calculations: Use get_width() and get_height() together to calculate aspect ratios and make intelligent processing decisions. This allows you to apply different strategies for landscape, portrait, and square images, ensuring optimal results for all orientations.