以编程方式插入 wordpress 附件后在屏幕上打印的图像内容


Image content printed on screen after inserting wordpress attachment programatically

我正在以编程方式为这样的帖子插入附件:

$wp_filetype = wp_check_filetype($gallery);
$attachment = array(
    'guid' => '', 
    'post_mime_type' => $wp_filetype['type'],
    'post_title' => preg_replace('/'.[^.]+$/', '', basename($gallery)),
    'post_content' => '',
    'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $gallery, $post_id );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $gallery ); 
$update_data = wp_update_attachment_metadata( $attach_id, $attach_data );

一切正常,附件已正确添加,但我的页面上显示了图像代码。 :S

像这样的东西(我不打算发布整个代码):

����JFIF``��;CREATOR: gd-jpeg v1.0 (using IJG JPEG v80), quality = 90 ��C     ��C         ����"��    ���}!1AQa"q2���#B��R��$3br� %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz��������������������������������������������������������������������������� ���w!1AQaq"2�B����    #3R�br� $4� 

知道为什么会这样吗?

您需要在发送图像内容之前在标头Content-Type: image/jpeg前面附加。

浏览器可以将文件内容解释为 jpeg 并正确显示。

使用 PHP: header("Content-Type: image/jpeg");