用php渲染图像并用html <img>标签输出

Rox*_*Rox 4 html php image render

我有一个带有几个可以渲染图像的函数的类。

// render.php
class Render {
   public function Render($some_arguments) {
      ...
      header("Content-Type: image/png");
        $im = @imagecreate(110, 20)
            or die("Cannot Initialize new GD image stream");
        $background_color = imagecolorallocate($im, 0, 0, 0);
        $text_color = imagecolorallocate($im, 233, 14, 91);
        imagestring($im, 1, 5, 5,  "A Simple Text String", $text_color);
        imagepng($im);
        return "data:image/png;base64,".base64_encode($im);
   }
}
Run Code Online (Sandbox Code Playgroud)

然后,我有一个包含html代码的php文件,我想在< img>标记中输出图像:

// index.php
include("render.php");
$render = new Render();
echo "<htlm><head></head><body>";
echo "<img src=\"".$render->Render(1)."\" />";
echo "</body></html>";
Run Code Online (Sandbox Code Playgroud)

当我在浏览器中运行index.php时,我只会得到一个空白屏幕。

我不能使用函数调用作为图像源吗?我知道我可以使用php文件作为源,例如< img src="render_image.php" />,但是后来我不能以面向对象的方式发送任何参数(我知道可以使用$ _GET来检索参数),但是我想使用一个很好的面向对象的方法来做书面代码。

那么,有什么方法可以将函数调用用作html标签的来源?

hyp*_*ypt 5

您可以对图像进行BASE64编码并使用数据url方案:

data:[<MIME-type>][;charset=<encoding>][;base64],<data>
Run Code Online (Sandbox Code Playgroud)

例如。

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot">
Run Code Online (Sandbox Code Playgroud)

因此,如果包括该图像而不是原始图像,则可以完全执行所需的操作。

(来自Wikipediea的示例)