Using WordPress ‘image_resize_dimensions()’ PHP function

The image_resize_dimensions WordPress PHP function calculates dimensions and coordinates for a resized image that fits within a specified width and height, with optional cropping behavior.

Usage

$new_dimensions = image_resize_dimensions($orig_w, $orig_h, $dest_w, $dest_h, $crop);

Parameters

  • $orig_w (int) – Original width in pixels.
  • $orig_h (int) – Original height in pixels.
  • $dest_w (int) – New width in pixels.
  • $dest_h (int) – New height in pixels.
  • $crop (bool|array) – Optional. Whether to crop image to specified width and height or resize. An array can specify positioning of the crop area. Default: false.

More information

See WordPress Developer Resources: image_resize_dimensions

Examples

Resizing an image without cropping

In this example, we’ll resize an image to 200×200 pixels without cropping it.

// Original dimensions
$orig_w = 500;
$orig_h = 300;

// New dimensions
$dest_w = 200;
$dest_h = 200;

// Calculate new dimensions
$new_dimensions = image_resize_dimensions($orig_w, $orig_h, $dest_w, $dest_h, false);

Resizing an image with cropping

In this example, we’ll resize and crop an image to 200×200 pixels using the center position for cropping.

// Original dimensions
$orig_w = 500;
$orig_h = 300;

// New dimensions
$dest_w = 200;
$dest_h = 200;

// Calculate new dimensions with cropping
$new_dimensions = image_resize_dimensions($orig_w, $orig_h, $dest_w, $dest_h, true);

Resizing and cropping with custom position

In this example, we’ll resize and crop an image to 200×200 pixels using a custom crop position.

// Original dimensions
$orig_w = 500;
$orig_h = 300;

// New dimensions
$dest_w = 200;
$dest_h = 200;

// Custom crop position
$crop_position = array('left', 'top');

// Calculate new dimensions with custom crop position
$new_dimensions = image_resize_dimensions($orig_w, $orig_h, $dest_w, $dest_h, $crop_position);

Resizing with different aspect ratios

In this example, we’ll resize an image to 200×300 pixels without cropping, maintaining aspect ratio.

// Original dimensions
$orig_w = 500;
$orig_h = 300;

// New dimensions
$dest_w = 200;
$dest_h = 300;

// Calculate new dimensions without cropping
$new_dimensions = image_resize_dimensions($orig_w, $orig_h, $dest_w, $dest_h, false);

Resizing and cropping a square image

In this example, we’ll resize and crop a 500×500 pixel image to 200×200 pixels.

// Original dimensions
$orig_w = 500;
$orig_h = 500;

// New dimensions
$dest_w = 200;
$dest_h = 200;

// Calculate new dimensions with cropping
$new_dimensions = image_resize_dimensions($orig_w, $orig_h, $dest_w, $dest_h, true);