使用两个函数输出图像内容类型

时间:2012-11-10 20:15:21

标签: php

我正在使用docroot之外的图像,并希望在函数内部显示该图像。

我如何正确地做到这一点?

以下是我到目前为止:(两个函数都在同一个文件中)

function page(){
  echo'
    test<br />
    '.output().'
  ';
}

function output(){
    header("Content-Type: image/gif");
    readfile( '../../../dirOutsideDocRoot/test.gif' );
}

目前这将输出图像,但我无法在其上方看到“测试”。是否可以使用header

将图像导入页面功能

3 个答案:

答案 0 :(得分:1)

您发送给客户端的最终内容只能有一种内容类型。 图片或文字。如果您想在一个页面中同时使用(当图像未写入文件时),您可以通过以下方式在base64中编写图像:

data:[<MIME-type>][;charset=<encoding>][;base64],<data>

在您的情况下,

data:image/gif;base64,<base64_encoded_image>

参见 Data URI scheme


以下内容适用:( 未经测试

$img = fread(fopen($path, "r"), filesize($path));
$base64 = "data:image/gif;base64," . base64_encode($img);

答案 1 :(得分:1)

听起来你要做的就是在同一页面上显示图像和文字。要做到这一点,你必须创建一个包含文本的页面,并且img标记指向另一个只返回图像的php页面。

您的Content-Type标题告诉浏览器整个页面都是图片。虽然,这不会发生,因为php会失败,说数据已经发送,因此无法输出标题。

希望这有帮助。

编辑:你也可以像Cthulhu说的那样用base64嵌入图像:

function output(){
    $imgbinary = fread(fopen('../../../dirOutsideDocRoot/test.gif', "r"), filesize($filename));
    echo '<img src="data:image/gif;base64,' . base64_encode($imgbinary).'" />';
}

有关php中base_64编码的更多信息,请参阅http://php.net/manual/en/function.base64-encode.php

答案 2 :(得分:1)

你应该有两个php页面:

第1页:

echo'
    test<br /><img src="page2.php"/>';

第2页:

header("Content-Type: image/gif");
readfile( '../../../dirOutsideDocRoot/test.gif' );