wp_image_matches_ratio

Helper function to test if aspect ratios for two images match.

Description

wp_image_matches_ratio( (int) $source_width, (int) $source_height, (int) $target_width, (int) $target_height ); 

Parameters (4)

0. $source_width (int)
Width of the first image in pixels.
1. $source_height (int)
Height of the first image in pixels.
2. $target_width (int)
Width of the second image in pixels.
3. $target_height (int)
Height of the second image in pixels.

Usage

  1. if ( !function_exists( 'wp_image_matches_ratio' ) ) { 
  2. require_once ABSPATH . WPINC . '/media.php'; 
  3.  
  4. // Width of the first image in pixels. 
  5. $source_width = -1; 
  6.  
  7. // Height of the first image in pixels. 
  8. $source_height = -1; 
  9.  
  10. // Width of the second image in pixels. 
  11. $target_width = -1; 
  12.  
  13. // Height of the second image in pixels. 
  14. $target_height = -1; 
  15.  
  16. // NOTICE! Understand what this does before running. 
  17. $result = wp_image_matches_ratio($source_width, $source_height, $target_width, $target_height); 
  18.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/media.php  
  1. function wp_image_matches_ratio( $source_width, $source_height, $target_width, $target_height ) { 
  2. /** 
  3. * To test for varying crops, we constrain the dimensions of the larger image 
  4. * to the dimensions of the smaller image and see if they match. 
  5. */ 
  6. if ( $source_width > $target_width ) { 
  7. $constrained_size = wp_constrain_dimensions( $source_width, $source_height, $target_width ); 
  8. $expected_size = array( $target_width, $target_height ); 
  9. } else { 
  10. $constrained_size = wp_constrain_dimensions( $target_width, $target_height, $source_width ); 
  11. $expected_size = array( $source_width, $source_height ); 
  12.  
  13. // If the image dimensions are within 1px of the expected size, we consider it a match. 
  14. $matched = ( abs( $constrained_size[0] - $expected_size[0] ) <= 1 && abs( $constrained_size[1] - $expected_size[1] ) <= 1 ); 
  15.  
  16. return $matched;