繁体   English   中英

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM