我在PHP中生成用于用户头像的图像。base64编码PHP生成的图像,而无需将图像写入磁盘
我首先对用户名进行散列处理,然后对散列的各种子字符串进行hexdec()
转换,以建立一组RGB颜色。
//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;
理想我不使用的中间步骤,并会跳过了写入图像到磁盘上,但我不知道如何最好地实现这一点?
我试过将$avatarImage
直接传递给base64_encode()
但是期望一个字符串,所以不起作用。
任何想法?