函数文档

stream_preview_image()

💡 云策文档标注

概述

stream_preview_image() 函数用于将文章中的图像流式传输到浏览器,并应用通过 $_REQUEST['history'] 传递的编辑更改。它处理图像缩放和预览生成,返回布尔值表示成功或失败。

关键要点

  • 函数接受一个必需的整数参数 $post_id,表示附件文章 ID。
  • 返回布尔值:成功时返回 true,失败时返回 false。
  • 内部使用 wp_get_image_editor() 加载图像编辑器,并应用来自 $_REQUEST['history'] 的 JSON 解码更改。
  • 通过 _image_get_preview_ratio() 计算预览比例,调整图像尺寸后使用 wp_stream_image() 输出到浏览器。
  • 相关函数包括 wp_raise_memory_limit()、image_edit_apply_changes() 和 wp_stream_image() 等。

代码示例

function stream_preview_image( $post_id ) {
    $post = get_post( $post_id );
    wp_raise_memory_limit( 'admin' );
    $img = wp_get_image_editor( _load_image_to_edit_path( $post_id ) );
    if ( is_wp_error( $img ) ) {
        return false;
    }
    $changes = ! empty( $_REQUEST['history'] ) ? json_decode( wp_unslash( $_REQUEST['history'] ) ) : null;
    if ( $changes ) {
        $img = image_edit_apply_changes( $img, $changes );
    }
    $size = $img->get_size();
    $w    = $size['width'];
    $h    = $size['height'];
    $ratio = _image_get_preview_ratio( $w, $h );
    $w2    = max( 1, $w * $ratio );
    $h2    = max( 1, $h * $ratio );
    if ( is_wp_error( $img->resize( $w2, $h2 ) ) ) {
        return false;
    }
    return wp_stream_image( $img, $post->post_mime_type, $post_id );
}

📄 原文内容

Streams image in post to browser, along with enqueued changes in $_REQUEST['history'].

Parameters

$post_idintrequired
Attachment post ID.

Return

bool True on success, false on failure.

Source

function stream_preview_image( $post_id ) {
	$post = get_post( $post_id );

	wp_raise_memory_limit( 'admin' );

	$img = wp_get_image_editor( _load_image_to_edit_path( $post_id ) );

	if ( is_wp_error( $img ) ) {
		return false;
	}

	$changes = ! empty( $_REQUEST['history'] ) ? json_decode( wp_unslash( $_REQUEST['history'] ) ) : null;
	if ( $changes ) {
		$img = image_edit_apply_changes( $img, $changes );
	}

	// Scale the image.
	$size = $img->get_size();
	$w    = $size['width'];
	$h    = $size['height'];

	$ratio = _image_get_preview_ratio( $w, $h );
	$w2    = max( 1, $w * $ratio );
	$h2    = max( 1, $h * $ratio );

	if ( is_wp_error( $img->resize( $w2, $h2 ) ) ) {
		return false;
	}

	return wp_stream_image( $img, $post->post_mime_type, $post_id );
}

Changelog

Version Description
2.9.0 Introduced.