2

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?

maxhb
  • 8,554
  • 9
  • 29
  • 53
Luke
  • 3,481
  • 6
  • 39
  • 63

2 Answers2

4

You can imagepng to a variable:

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

//whatever image manipulations you do

//write the image to a variable
ob_start();
imagepng($avatarImage);
$imagePng = ob_get_contents();
ob_end_clean();

//base64 encode
$imageData = base64_encode($imagePng);

//continue
Alex Blex
  • 34,704
  • 7
  • 48
  • 75
1

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);
}
maxhb
  • 8,554
  • 9
  • 29
  • 53