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

Dentra Andres picture Dentra Andres · Jan 11, 2012 · Viewed 16k times · Source

I'm trying to create a way to show an image created with PHP/GD, in an OOP fashion. In order to accomplish that, I created a class that, among other things, creates an image. Something like this:

<?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
?>

I tried to create a function within the class that would output the image. Something like this:

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

but it didn't work. I also tried

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

but this also didn't work. The idea was to simply call the function from the HTML. Like this:

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

Am I going all wrong on this? Is there a way to accomplish what I want? I tried to think of a way to use the img='mycode.php' but it doesn't work for me because the class has to be created before the page loads and the image appears half way through the page.

Thanks.

Answer

SteAp picture SteAp · Jan 11, 2012

First, you need to insert a second parameter to imagejpeg() to allow 100 to be the quality parameter. Then, you need to base64-encode the raw bytes:

    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 ) . "' />";

    }

The data:image/jpeg;base64 requires the raw bytes to get encoded as base64.

Additionally, I'd propose to make $image a protected variable, since I suppose it is created and maintained solely inside of MyClass.