wp_get_image_editor()
云策文档标注
概述
wp_get_image_editor() 函数用于获取一个 WP_Image_Editor 实例并加载指定图像文件,支持图像编辑操作。它通过内部逻辑自动选择图像编辑器实现,并处理文件类型检测和输出格式映射。
关键要点
- 函数返回 WP_Image_Editor 对象或 WP_Error 对象,用于图像编辑任务
- 参数包括必需的 $path(文件路径)和可选的 $args 数组,用于传递额外参数如 mime_type
- 内部自动调用 wp_check_filetype() 检测文件类型,并设置输出格式
- 使用 _wp_image_editor_choose() 选择编辑器实现,如 GD 或 Imagick
- 成功时返回加载的编辑器实例,失败时返回 WP_Error
代码示例
$image = wp_get_image_editor( 'cool_image.jpg' );
if ( ! is_wp_error( $image ) ) {
$image->rotate( 90 );
$image->resize( 300, 300, true );
$image->save( 'new_image.jpg' );
}注意事项
- 确保文件路径正确且图像格式受支持,否则可能返回 WP_Error
- 函数自 WordPress 3.5.0 引入,广泛用于图像处理相关功能如生成缩略图
- 相关函数包括 wp_get_image_editor_output_format() 和 wp_check_filetype(),用于辅助处理
原文内容
Returns a WP_Image_Editor instance and loads file into it.
Parameters
$pathstringrequired-
Path to the file to load.
$argsarrayoptional-
Additional arguments for retrieving the image editor.
Default:
array()
Source
function wp_get_image_editor( $path, $args = array() ) {
$args['path'] = $path;
// If the mime type is not set in args, try to extract and set it from the file.
if ( ! isset( $args['mime_type'] ) ) {
$file_info = wp_check_filetype( $args['path'] );
/*
* If $file_info['type'] is false, then we let the editor attempt to
* figure out the file type, rather than forcing a failure based on extension.
*/
if ( isset( $file_info ) && $file_info['type'] ) {
$args['mime_type'] = $file_info['type'];
}
}
// Check and set the output mime type mapped to the input type.
if ( isset( $args['mime_type'] ) ) {
$output_format = wp_get_image_editor_output_format( $path, $args['mime_type'] );
if ( isset( $output_format[ $args['mime_type'] ] ) ) {
$args['output_mime_type'] = $output_format[ $args['mime_type'] ];
}
}
$implementation = _wp_image_editor_choose( $args );
if ( $implementation ) {
$editor = new $implementation( $path );
$loaded = $editor->load();
if ( is_wp_error( $loaded ) ) {
return $loaded;
}
return $editor;
}
return new WP_Error( 'image_no_editor', __( 'No editor could be selected.' ) );
}
Changelog
| Version | Description |
|---|---|
| 3.5.0 | Introduced. |
Skip to note 3 content
Codex
Basic Example
$image = wp_get_image_editor( 'cool_image.jpg' ); if ( ! is_wp_error( $image ) ) { $image->rotate( 90 ); $image->resize( 300, 300, true ); $image->save( 'new_image.jpg' ); }Skip to note 4 content
Hyppolite T.
Example: Check a broken image
$image = wp_get_image_editor( 'my_image.jpg' ); if ( is_wp_error( $image ) ) { //do some action, like add image path and name to an array of broken images. }