2016-01-27 42 views
1

我在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()但是期望一个字符串,所以不起作用。

任何想法?

回答

1

您可以使用输出缓冲来捕捉图像数据,然后使用它作为期望:

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

为了方便,你可以创建一个新功能处理图像编码:

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

    return base64_encode($imgData); 
} 
2

可以imagepng给一个变量:

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