wp_image_matches_ratio

函数
wp_image_matches_ratio ( $source_width, $source_height, $target_width, $target_height )
参数
  • (int) $source_width Width of the first image in pixels.
    Required:
  • (int) $source_height Height of the first image in pixels.
    Required:
  • (int) $target_width Width of the second image in pixels.
    Required:
  • (int) $target_height Height of the second image in pixels.
    Required:
返回值
  • (bool) True if aspect ratios match within 1px. False if not.
定义位置
相关方法
wp_media_attach_actionwp_get_attachment_captionwp_image_file_matches_image_metawp_image_editorimage_add_caption
引入
4.6.0
弃用
-

wp_image_matches_ratio: 这个函数用来检查一个图像是否与另一个图像有相同的长宽比。它需要两个参数,第一个是第一个图像的图像元数据的数组,第二个是第二个图像的图像元数据的数组。如果这两张图片有相同的长宽比,则返回true,否则返回false。

帮助函数,测试两张图片的长宽比是否匹配。

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;
}

常见问题

FAQs
查看更多 >