Search code examples
phpimagebase64php-gd

base64 encode PHP generated image without writing the image to disk


I'm generating an image in PHP for use in a users avatar.

I start by hashing the username and then doing a hexdec() conversion on various substrings of the hash to build up a set of RGB colours.

//create image
$avatarImage = imagecreate(250, 250);

// first call to imagecolorallocate sets the background colour
$background = imagecolorallocate($avatarImage, hexdec(substr($hash, 0, 2)), hexdec(substr($hash, 2, 2)), hexdec(substr($hash, 4, 2)));

//write the image to a file
$imageFile = 'image.png';
imagepng($avatarImage, $imageFile);

//load file contents and base64 encode
$imageData = base64_encode(file_get_contents($imageFile));

//build $src dataURI.
$src = 'data: ' . mime_content_type($imageFile) . ';base64,' . $imageData;

Ideally I'd not use the intermediate step and would skip writing the image out onto disk, although I'm not sure how best to implement this?

I've tried passing $avatarImage directly to base64_encode() but that expects a string so doesn't work.

Any ideas?


Solution

  • You can use output buffering to capture the image data and then use it as desired:

    ob_start ( ); // Start buffering
    imagepng($avatarImage); // output image
    $imageData = ob_get_contents ( ); // store image data
    ob_end_clean ( ); // end and clear buffer
    

    For convenience you could create a new function to handle image encoding:

    function createBase64FromImageResource($imgResource) {
      ob_start ( );
      imagepng($imgResource);
      $imgData = ob_get_contents ( );
      ob_end_clean ( );
    
      return base64_encode($imgData);
    }