<?php
// 引入必要的库,这里使用的是wkhtmltoimage工具,它需要预先安装在服务器上
// 可以通过命令行工具或者PHP扩展来调用
function htmlToImage($html, $outputPath) {
// 创建临时HTML文件
$tempHtmlFile = tempnam(sys_get_temp_dir(), 'html');
file_put_contents($tempHtmlFile, $html);
// 调用wkhtmltoimage命令将HTML转换为图片
$command = sprintf('wkhtmltoimage %s %s', escapeshellarg($tempHtmlFile), escapeshellarg($outputPath));
exec($command, $output, $returnVar);
// 删除临时HTML文件
unlink($tempHtmlFile);
// 检查命令是否成功执行
if ($returnVar !== 0) {
throw new Exception("Failed to convert HTML to image. Error: " . implode("\n", $output));
}
return $outputPath;
}
try {
// 示例HTML内容
$htmlContent = '<html><body><h1>Hello, World!</h1></body></html>';
// 输出图片路径
$imagePath = __DIR__ . '/output.png';
// 调用函数进行转换
$result = htmlToImage($htmlContent, $imagePath);
echo "Image successfully created at: " . $result;
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
?>
wkhtmltoimage工具,我们首先将其写入一个临时文件。exec函数调用wkhtmltoimage命令,将临时HTML文件转换为图片并保存到指定路径。如果你没有安装wkhtmltoimage,可以从官方网站下载并安装。
上一篇:php static
下一篇:php转字符串
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站