image_make_intermediate_size()
云策文档标注
概述
image_make_intermediate_size() 是 WordPress 中用于调整图像尺寸以生成缩略图或中间尺寸图片的核心函数。它基于指定的宽度、高度和裁剪参数处理图像文件,并返回包含文件大小、宽度和高度的元数据数组。
关键要点
- 函数接受四个参数:文件路径(必需)、宽度(必需)、高度(必需)和裁剪行为(可选,默认为 false)。
- 裁剪参数可以是布尔值或数组:false 表示缩放,true 表示居中裁剪,数组允许指定 x 和 y 方向的裁剪位置(如 'left'、'center')。
- 成功时返回元数据数组(包含文件大小、宽度、高度),失败时返回 false。
- 内部使用 wp_get_image_editor() 获取图像编辑器实例,并通过 resize() 方法执行调整操作。
- 可通过 'image_make_intermediate_size' filter 钩子修改返回的数组值。
代码示例
function image_make_intermediate_size( $file, $width, $height, $crop = false ) {
if ( $width || $height ) {
$editor = wp_get_image_editor( $file );
if ( is_wp_error( $editor ) || is_wp_error( $editor->resize( $width, $height, $crop ) ) ) {
return false;
}
$resized_file = $editor->save();
if ( ! is_wp_error( $resized_file ) && $resized_file ) {
unset( $resized_file['path'] );
return $resized_file;
}
}
return false;
}注意事项
- 函数在 WordPress 2.5.0 版本中引入,是图像处理的基础功能之一。
- 相关函数包括 wp_get_image_editor() 和 is_wp_error(),用于获取图像编辑器和错误检查。
- 确保文件路径有效,否则可能导致 wp_get_image_editor() 返回 WP_Error。
原文内容
Resizes an image to make a thumbnail or intermediate size.
Description
The returned array has the file size, the image width, and image height. The ‘image_make_intermediate_size’ filter can be used to hook in and change the values of the returned array. The only parameter is the resized file path.
Parameters
$filestringrequired-
File path.
$widthintrequired-
Image width.
$heightintrequired-
Image height.
$cropbool|arrayoptional-
Image cropping behavior. If false, the image will be scaled (default).
If true, image will be cropped to the specified dimensions using center positions.
If an array, the image will be cropped using the array to specify the crop location:0stringThe x crop position. Accepts'left','center', or'right'.1stringThe y crop position. Accepts'top','center', or'bottom'.
Default:
false
Source
function image_make_intermediate_size( $file, $width, $height, $crop = false ) {
if ( $width || $height ) {
$editor = wp_get_image_editor( $file );
if ( is_wp_error( $editor ) || is_wp_error( $editor->resize( $width, $height, $crop ) ) ) {
return false;
}
$resized_file = $editor->save();
if ( ! is_wp_error( $resized_file ) && $resized_file ) {
unset( $resized_file['path'] );
return $resized_file;
}
}
return false;
}
Changelog
| Version | Description |
|---|---|
| 2.5.0 | Introduced. |