The get_udims() WordPress PHP function calculates the new dimensions for a downsampled image.
Usage
$new_dimensions = get_udims( $current_width, $current_height );
Parameters
$width
(int) – Required. Current width of the image.$height
(int) – Required. Current height of the image.
More information
See WordPress Developer Resources: get_udims()
Examples
Reducing Image Size by Half
This example calculates the dimensions for an image that needs to be reduced by 50%.
$current_width = 800; $current_height = 600; $scale_factor = 0.5; $new_width = $current_width * $scale_factor; $new_height = $current_height * $scale_factor; $new_dimensions = get_udims( $new_width, $new_height );
Maintaining Aspect Ratio
This example maintains the aspect ratio while resizing an image to a maximum width of 400px.
$current_width = 800; $current_height = 600; $max_width = 400; $scale_factor = $max_width / $current_width; $new_width = $current_width * $scale_factor; $new_height = $current_height * $scale_factor; $new_dimensions = get_udims( $new_width, $new_height );
Resizing Image Based on Height
This example resizes an image based on a maximum height of 300px, maintaining its aspect ratio.
$current_width = 800; $current_height = 600; $max_height = 300; $scale_factor = $max_height / $current_height; $new_width = $current_width * $scale_factor; $new_height = $current_height * $scale_factor; $new_dimensions = get_udims( $new_width, $new_height );
Resizing Image Based on Smallest Dimension
This example resizes an image based on the smallest dimension, in this case, the height, with a target of 200px.
$current_width = 800; $current_height = 600; $target_dimension = 200; $scale_factor = min( $current_width, $current_height ) / $target_dimension; $new_width = $current_width * $scale_factor; $new_height = $current_height * $scale_factor; $new_dimensions = get_udims( $new_width, $new_height );
Resizing Image Based on Largest Dimension
This example resizes an image based on the largest dimension, in this case, the width, with a target of 600px.
$current_width = 800; $current_height = 600; $target_dimension = 600; $scale_factor = max( $current_width, $current_height ) / $target_dimension; $new_width = $current_width * $scale_factor; $new_height = $current_height * $scale_factor; $new_dimensions = get_udims( $new_width, $new_height );