image_resize()
云策文档标注
概述
image_resize() 是一个已弃用的 WordPress 函数,用于缩放图像以适应指定尺寸并保存新副本。它支持 PNG、GIF 和 JPEG 格式,并保留 PNG 透明度。自 WordPress 3.5.0 起,建议使用 wp_get_image_editor() 替代。
关键要点
- 函数功能:缩放图像至最大宽度和高度,可选裁剪,并保存为新文件。
- 支持格式:PNG、GIF、JPEG,PNG 透明度会被保留。
- 弃用状态:自 WordPress 3.5.0 起弃用,推荐使用 wp_get_image_editor() 进行图像处理。
- 参数说明:包括文件路径、最大宽度、最大高度、裁剪标志、后缀、目标路径和 JPEG 质量等。
- 返回值:失败时返回 WP_Error,成功时返回新文件路径字符串。
- 依赖关系:功能可能受 PHP 版本影响,某些 API 缺失会导致支持降级。
代码示例
function image_resize( $file, $max_w, $max_h, $crop = false, $suffix = null, $dest_path = null, $jpeg_quality = 90 ) {
_deprecated_function( __FUNCTION__, '3.5.0', 'wp_get_image_editor()' );
$editor = wp_get_image_editor( $file );
if ( is_wp_error( $editor ) )
return $editor;
$editor->set_quality( $jpeg_quality );
$resized = $editor->resize( $max_w, $max_h, $crop );
if ( is_wp_error( $resized ) )
return $resized;
$dest_file = $editor->generate_filename( $suffix, $dest_path );
$saved = $editor->save( $dest_file );
if ( is_wp_error( $saved ) )
return $saved;
return $dest_file;
}注意事项
- 此函数已弃用,新代码应使用 wp_get_image_editor() 以避免兼容性问题。
- 图像处理功能依赖于 PHP 版本,某些版本可能不支持全部特性,这并非 WordPress 缺陷。
- 相关函数包括 wp_get_image_editor()、_deprecated_function() 和 is_wp_error()。
原文内容
Scale down an image to fit a particular size and save a new copy of the image.
Description
The PNG transparency will be preserved using the function, as well as the image type. If the file going in is PNG, then the resized image is going to be PNG. The only supported image types are PNG, GIF, and JPEG.
Some functionality requires API to exist, so some PHP version may lose out support. This is not the fault of WordPress (where functionality is downgraded, not actual defects), but of your PHP version.
See also
Parameters
$filestringrequired-
Image file path.
$max_wintrequired-
Maximum width to resize to.
$max_hintrequired-
Maximum height to resize to.
$cropbooloptional-
Whether to crop image or resize.
Default:
false $suffixstringoptional-
File suffix.
Default:
null $dest_pathstringoptional-
New image file path.
Default:
null $jpeg_qualityintoptional-
Image quality percentage.
Default:
90
Source
function image_resize( $file, $max_w, $max_h, $crop = false, $suffix = null, $dest_path = null, $jpeg_quality = 90 ) {
_deprecated_function( __FUNCTION__, '3.5.0', 'wp_get_image_editor()' );
$editor = wp_get_image_editor( $file );
if ( is_wp_error( $editor ) )
return $editor;
$editor->set_quality( $jpeg_quality );
$resized = $editor->resize( $max_w, $max_h, $crop );
if ( is_wp_error( $resized ) )
return $resized;
$dest_file = $editor->generate_filename( $suffix, $dest_path );
$saved = $editor->save( $dest_file );
if ( is_wp_error( $saved ) )
return $saved;
return $dest_file;
}
Changelog
| Version | Description |
|---|---|
| 3.5.0 | Deprecated. Use wp_get_image_editor() |
| 2.5.0 | Introduced. |