函数文档

wp_load_image()

💡 云策文档标注

概述

wp_load_image() 是一个已弃用的 WordPress 函数,用于从字符串加载图像,前提是 PHP 支持 GD 库。该函数在 WordPress 3.5.0 中被标记为弃用,建议使用 wp_get_image_editor() 替代。

关键要点

  • 函数 wp_load_image() 已弃用,自 WordPress 3.5.0 起推荐使用 wp_get_image_editor()。
  • 参数 $file 是必需的,可以是文件名或附件 ID,函数会检查文件是否存在和是否为有效图像。
  • 返回值为图像资源(如 GdImage)或错误字符串,依赖于 GD 库的 imagecreatefromstring() 函数。
  • 函数内部会调用 wp_raise_memory_limit() 来提升内存限制,以处理 GD 库的内存使用。

代码示例

function wp_load_image( $file ) {
    _deprecated_function( __FUNCTION__, '3.5.0', 'wp_get_image_editor()' );

    if ( is_numeric( $file ) )
        $file = get_attached_file( $file );

    if ( ! is_file( $file ) ) {
        /* translators: %s: File name. */
        return sprintf( __( 'File “%s” does not exist?' ), $file );
    }

    if ( ! function_exists('imagecreatefromstring') )
        return __('The GD image library is not installed.');

    // Set artificially high because GD uses uncompressed images in memory.
    wp_raise_memory_limit( 'image' );

    $image = imagecreatefromstring( file_get_contents( $file ) );

    if ( ! is_gd_image( $image ) ) {
        /* translators: %s: File name. */
        return sprintf( __( 'File “%s” is not an image.' ), $file );
    }

    return $image;
}

注意事项

  • 此函数已弃用,新代码应避免使用,转而使用 wp_get_image_editor() 进行图像处理。
  • 依赖 GD 库,如果未安装或不可用,函数会返回错误信息。
  • 函数会检查文件是否存在和是否为有效图像,返回相应的错误字符串。

📄 原文内容

Load an image from a string, if PHP supports it.

Description

See also

Parameters

$filestringrequired
Filename of the image to load.

Return

resource|GdImage|string The resulting image resource or GdImage instance on success, error string on failure.

Source

function wp_load_image( $file ) {
	_deprecated_function( __FUNCTION__, '3.5.0', 'wp_get_image_editor()' );

	if ( is_numeric( $file ) )
		$file = get_attached_file( $file );

	if ( ! is_file( $file ) ) {
		/* translators: %s: File name. */
		return sprintf( __( 'File “%s” does not exist?' ), $file );
	}

	if ( ! function_exists('imagecreatefromstring') )
		return __('The GD image library is not installed.');

	// Set artificially high because GD uses uncompressed images in memory.
	wp_raise_memory_limit( 'image' );

	$image = imagecreatefromstring( file_get_contents( $file ) );

	if ( ! is_gd_image( $image ) ) {
		/* translators: %s: File name. */
		return sprintf( __( 'File “%s” is not an image.' ), $file );
	}

	return $image;
}

Changelog

Version Description
3.5.0 Deprecated. Use wp_get_image_editor()
2.1.0 Introduced.