我可以在不保存和不使用带图像头的外部PHP的情况下显示用PHP/GD创建的图像吗


Can I display an image created with PHP/GD without saving and without using external PHP with image header?

我正在尝试创建一种方法,以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
?>

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

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

但没有奏效。我也试过

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

但这也没有奏效。其想法是简单地从HTML中调用函数。像这样:

<div id='anyid'>
    <?php $myvar->show(); ?>
</div>

我是不是完全错了?有办法实现我想要的吗?我试着想出一种方法来使用img='mycode.php',但它对我来说不起作用,因为必须在加载页面之前创建类,并且图像显示在页面的一半。

谢谢。

首先,需要向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 ) . "' />";
    }

data:image/jpeg;base64需要原始字节编码为base64

此外,我建议将$image设为protected变量,因为我认为它仅在MyClass内部创建和维护。

一行代码,盲搜索3小时后解决我!

...
ob_start();
header( "Content-type: image/jpeg" ); <br/>
imagejpeg( $this->img, NULL, $qualidade );<br/>
imagedestroy( $this->img );<br/>
$i = ob_get_clean();<br/>
echo "<img src='data:image/jpeg;base64," . base64_encode( $i )."'>";   //saviour line!

啊!