Advertisements

wp_constrain_dimensions

Definition:
function wp_constrain_dimensions( $current_width, $current_height, $max_width=0, $max_height=0 ) {}

Calculates the new dimensions for a downsampled image.
If either width or height are empty, no constraint is applied on that dimension.

Parameters

  • int $current_width: Current width of the image.
  • int $current_height: Current height of the image.
  • int $max_width: Optional. Maximum wanted width.
  • int $max_height: Optional. Maximum wanted height.

Return values

returns:First item is the width, the second item is the height.

Source code

function wp_constrain_dimensions( $current_width, $current_height, $max_width=0, $max_height=0 ) {

	if ( !$max_width and !$max_height )

		return array( $current_width, $current_height );



	$width_ratio = $height_ratio = 1.0;

	$did_width = $did_height = false;



	if ( $max_width > 0 && $current_width > 0 && $current_width > $max_width ) {

		$width_ratio = $max_width / $current_width;

		$did_width = true;

	}



	if ( $max_height > 0 && $current_height > 0 && $current_height > $max_height ) {

		$height_ratio = $max_height / $current_height;

		$did_height = true;

	}



	// Calculate the larger/smaller ratios

	$smaller_ratio = min( $width_ratio, $height_ratio );

	$larger_ratio  = max( $width_ratio, $height_ratio );



	if ( intval( $current_width * $larger_ratio ) > $max_width || intval( $current_height * $larger_ratio ) > $max_height )

 		// The larger ratio is too big. It would result in an overflow.

		$ratio = $smaller_ratio;

	else

		// The larger ratio fits, and is likely to be a more "snug" fit.

		$ratio = $larger_ratio;



	$w = intval( $current_width  * $ratio );

	$h = intval( $current_height * $ratio );



	// Sometimes, due to rounding, we'll end up with a result like this: 465x700 in a 177x177 box is 117x176... a pixel short

	// We also have issues with recursive calls resulting in an ever-changing result. Constraining to the result of a constraint should yield the original result.

	// Thus we look for dimensions that are one pixel shy of the max value and bump them up

	if ( $did_width && $w == $max_width - 1 )

		$w = $max_width; // Round it up

	if ( $did_height && $h == $max_height - 1 )

		$h = $max_height; // Round it up



	return array( $w, $h );

}

3487

Advertisements

No comments yet... Be the first to leave a reply!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: