我用ImagePng()创建了一个图像.我不希望它将图像保存到文件系统,但想要在与base64编码内联图像相同的页面上输出它,就像
print '<p><img src="data:image/png;base64,'.base64_encode(ImagePng($png)).'" alt="image 1" width="96" height="48"/></p>';
Run Code Online (Sandbox Code Playgroud)
这不起作用.
这可能在一个PHP文件中完成吗?
提前致谢!
Mic*_*ski 29
这里的技巧是使用输出缓冲来捕获输出imagepng()
,输出将输出发送到浏览器或文件.它不会将其返回存储在变量(或base64编码)中:
// Enable output buffering
ob_start();
imagepng($png);
// Capture the output and clear the output buffer
$imagedata = ob_get_clean();
print '<p><img src="data:image/png;base64,'.base64_encode($imagedata).'" alt="image 1" width="96" height="48"/></p>';
Run Code Online (Sandbox Code Playgroud)
这是根据文档中的用户示例改编的imagepng()
.
在使用PHP和AJAX时我使用ob_get_contents()时遇到了麻烦,所以我尝试了这个:
$id = generateID(); //Whereas this generates a random ID number
$file="testimage".$id.".png";
imagepng($image, $file);
imagedestroy($image);
echo(base64_encode(file_get_contents($file)));
unlink($file);
Run Code Online (Sandbox Code Playgroud)
这会在服务器上保存临时图像文件,然后在编码和回显后将其删除.