wp_image_matches_ratio()
云策文档标注
概述
wp_image_matches_ratio() 是一个辅助函数,用于测试两个图像的宽高比是否匹配。它通过比较图像尺寸,在1像素容差范围内判断宽高比是否一致。
关键要点
- 函数接受四个整数参数:$source_width、$source_height、$target_width、$target_height,分别表示两个图像的宽度和高度。
- 返回布尔值:如果宽高比在1像素内匹配则返回 true,否则返回 false。
- 内部使用 wp_constrain_dimensions() 和 wp_fuzzy_number_match() 函数进行计算和容差判断。
- 主要用于图像处理场景,如 srcset 属性计算和中间尺寸检索。
代码示例
function wp_image_matches_ratio( $source_width, $source_height, $target_width, $target_height ) {
if ( $source_width > $target_width ) {
$constrained_size = wp_constrain_dimensions( $source_width, $source_height, $target_width );
$expected_size = array( $target_width, $target_height );
} else {
$constrained_size = wp_constrain_dimensions( $target_width, $target_height, $source_width );
$expected_size = array( $source_width, $source_height );
}
$matched = ( wp_fuzzy_number_match( $constrained_size[0], $expected_size[0] ) && wp_fuzzy_number_match( $constrained_size[1], $expected_size[1] ) );
return $matched;
}注意事项
- 函数自 WordPress 4.6.0 版本引入。
- 依赖 wp_constrain_dimensions() 和 wp_fuzzy_number_match() 函数,确保这些函数可用。
- 常用于 wp_calculate_image_srcset() 和 image_get_intermediate_size() 等图像处理函数中。
原文内容
Helper function to test if aspect ratios for two images match.
Parameters
$source_widthintrequired-
Width of the first image in pixels.
$source_heightintrequired-
Height of the first image in pixels.
$target_widthintrequired-
Width of the second image in pixels.
$target_heightintrequired-
Height of the second image in pixels.
Source
function wp_image_matches_ratio( $source_width, $source_height, $target_width, $target_height ) {
/*
* To test for varying crops, we constrain the dimensions of the larger image
* to the dimensions of the smaller image and see if they match.
*/
if ( $source_width > $target_width ) {
$constrained_size = wp_constrain_dimensions( $source_width, $source_height, $target_width );
$expected_size = array( $target_width, $target_height );
} else {
$constrained_size = wp_constrain_dimensions( $target_width, $target_height, $source_width );
$expected_size = array( $source_width, $source_height );
}
// If the image dimensions are within 1px of the expected size, we consider it a match.
$matched = ( wp_fuzzy_number_match( $constrained_size[0], $expected_size[0] ) && wp_fuzzy_number_match( $constrained_size[1], $expected_size[1] ) );
return $matched;
}
Changelog
| Version | Description |
|---|---|
| 4.6.0 | Introduced. |