我可以显示使用PHP/GD创建的图像而无需保存,也不使用带有图像标题的外部PHP吗?

Den*_*res 10 php gd image

我正在尝试创建一种以OOP方式显示使用PHP/GD创建的图像的方法.为了实现这一目标,我创建了一个类,除其他外,创建了一个图像.像这样的东西:

<?php
    class MyClass 
    {
        public $image;
        function __construct()
        {
           ...
           $this->image = imagecreatetruecolor(100,100);
           $bg = imagecolorallocate($this->image,100,100,100);
           imagefilledrectangle($this->image,0,0,100,100,$bg);
           ...
        }
        ...
    }

    $myvar = new MyClass
?>
Run Code Online (Sandbox Code Playgroud)

我试图在类中创建一个输出图像的函数.像这样的东西:

function show()
{
    echo "<img src='" . imagejpeg($this->image,100) . "' />";
}
Run Code Online (Sandbox Code Playgroud)

但它不起作用.我也试过了

function show()
{
    echo "<img src='data:image/jpeg;base64," . imagejpeg($this->image,100) . "' />";
}
Run Code Online (Sandbox Code Playgroud)

但这也行不通.想法是简单地从HTML调用函数.像这样:

<div id='anyid'>
    <?php $myvar->show(); ?>
</div>
Run Code Online (Sandbox Code Playgroud)

我这么错了吗?有没有办法实现我想要的?我试着想办法使用img ='mycode.php',但它对我不起作用,因为必须在页面加载之前创建类,图像出现在页面的一半.

谢谢.

Ste*_*eAp 33

首先,您需要插入第二个参数imagejpeg()以允许100作为质量参数.然后,您需要对原始字节进行base64编码:

    public function show() {

        // Begin capturing the byte stream
        ob_start();

        // generate the byte stream
        imagejpeg($this->image, NULL, 100);

        // and finally retrieve the byte stream
        $rawImageBytes = ob_get_clean();

        echo "<img src='data:image/jpeg;base64," . base64_encode( $rawImageBytes ) . "' />";

    }
Run Code Online (Sandbox Code Playgroud)

data:image/jpeg;base64要求得到按Base64编码的原始字节.

另外,我建议创建$image一个protected变量,因为我认为它只是在内部创建和维护MyClass.