base64 对 PHP 生成的映像进行编码,而无需将映像写入磁盘


base64 encode PHP generated image without writing the image to disk

我正在用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()但这需要一个字符串,所以不起作用。

有什么想法吗?

您可以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

您可以使用输出缓冲来捕获图像数据,然后根据需要使用它:

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);
}