缩放图像以适合特定大小(例如“拇指”或“中等”)。

原型

image_downsize( int $id, array|string $size = 'medium' )

描述

具有图像URL,宽度,高度以及是否为中间大小的数组,返回成功时返回的顺序。如果$ url是调整大小的图像,$ is_intermediate为true,如果是原始图像则为false。

参数

$id (int) (Required) 图像的附件ID。

$size (array|string) (Optional)  要缩放的图像大小。接受任何有效的图像大小,或以像素为单位的宽度和高度值数组(按此顺序)。

返回值

(false|array)  包含图像URL,宽度,高度和布尔值的数组,用于表示图像是否为中间大小。失败时是假的。

源文件

路径:wp-includes/media.php

<?php
...
function image_downsize( $id, $size = 'medium' ) {
	$is_image = wp_attachment_is_image( $id );
	/**
	 * Filters whether to preempt the output of image_downsize().
	 *
	 * Passing a truthy value to the filter will effectively short-circuit
	 * down-sizing the image, returning that value as output instead.
	 *
	 * @since 2.5.0
	 *
	 * @param bool         $downsize Whether to short-circuit the image downsize. Default false.
	 * @param int          $id       Attachment ID for image.
	 * @param array|string $size     Size of image. Image size or array of width and height values (in that order).
	 *                               Default 'medium'.
	 */
	if ( $out = apply_filters( 'image_downsize', false, $id, $size ) ) {
		return $out;
	}
	$img_url = wp_get_attachment_url($id);
	$meta = wp_get_attachment_metadata($id);
	$width = $height = 0;
	$is_intermediate = false;
	$img_url_basename = wp_basename($img_url);
	// If the file isn't an image, attempt to replace its URL with a rendered image from its meta.
	// Otherwise, a non-image type could be returned.
	if ( ! $is_image ) {
		if ( ! empty( $meta['sizes'] ) ) {
			$img_url = str_replace( $img_url_basename, $meta['sizes']['full']['file'], $img_url );
			$img_url_basename = $meta['sizes']['full']['file'];
			$width = $meta['sizes']['full']['width'];
			$height = $meta['sizes']['full']['height'];
		} else {
			return false;
		}
	}
	// try for a new style intermediate size
	if ( $intermediate = image_get_intermediate_size($id, $size) ) {
		$img_url = str_replace($img_url_basename, $intermediate['file'], $img_url);
		$width = $intermediate['width'];
		$height = $intermediate['height'];
		$is_intermediate = true;
	}
	elseif ( $size == 'thumbnail' ) {
		// fall back to the old thumbnail
		if ( ($thumb_file = wp_get_attachment_thumb_file($id)) && $info = getimagesize($thumb_file) ) {
			$img_url = str_replace($img_url_basename, wp_basename($thumb_file), $img_url);
			$width = $info[0];
			$height = $info[1];
			$is_intermediate = true;
		}
	}
	if ( !$width && !$height && isset( $meta['width'], $meta['height'] ) ) {
		// any other type: use the real image
		$width = $meta['width'];
		$height = $meta['height'];
	}
	if ( $img_url) {
		// we have the actual image size, but might need to further constrain it if content_width is narrower
		list( $width, $height ) = image_constrain_size_for_editor( $width, $height, $size );
		return array( $img_url, $width, $height, $is_intermediate );
	}
	return false;
}
...
?>

其他

英文文档:https://developer.wordpress.org/reference/functions/image_downsize/