如何用PHP脚本和Linux命令行创建网站(html)的截图

时间:2019-05-19 01:25:49  来源:igfitidea点击:

Wkhtmltoimage是一个非常有用的应用程序来创建一个网站或网页的截图。
有时我们需要创建网页的截图并存储到我们的系统中。
它使用QT Webkit渲染引擎来创建各种格式的图像。
本文将使用php脚本和Linux命令行捕获网页的屏幕截图。

步骤1:在Linux中安装wkhtmltoimage

按照以下步骤从linux系统下载wkhtmltoimage并安装到linux系统上。

# cd /opt
# wget http://downloads.sourceforge.net/project/wkhtmltopdf/0.12.0/wkhtmltox-linux-i386_0.12.0-03c001d.tar.xz
# tar xJf wkhtmltox-linux-i386_0.12.0-03c001d.tar.xz
# ln -s /opt/wkhtmltox/bin/wkhtmltoimage /usr/bin/wkhtmltoimage
# chown apache:apache /usr/bin/wkhtmltoimage
# chmod +x /usr/bin/wkhtmltoimage

第2步:使用命令行创建图片

首先使用linux命令行检查wkhtmltoimage脚本。
下面的命令将对http://google.com屏幕截图,并创建名称为google.jpg的图片。

# /usr/bin/wkhtmltoimage --no-images --load-error-handling ignore http://google.com google.jpg

步骤3:创建图片的PHP代码

使用以下php代码从html(网站url)生成图像。
这个脚本需要为Apache启用shell_exec函数。
大多数共享主机提供商不允许这个功能。
创建一个文件名 getImage.php,并放入以下代码:

<?php

$url = $_GET['url'];    // Website URL to Create Image
$name = $_GET['img'];   // Output Image Name
$command = "/usr/bin/wkhtmltoimage --no-images --load-error-handling ignore";
$dir_img = "/var/www/html/images/";     // Image files will be saved here
$ex_cmd = "$command $url " . $dir_img . $name;
$output = shell_exec($ex_cmd);
?>

使用以下syntex或演示url生成网站图片(html)。
语法:
http://youdomain.com/getImage.php?url=<website url>&img=<image name>

例子:
https://theitroad.com/getImage.php?url=http://google.com&img=image1.jpg

步骤4:SEO友好URL的PHP脚本

如果你想为这个设置创建SEO友好的URL,你可以使用下面的步骤。
在web服务器文档根目录中创建几个必需的目录

# mkdir -p /var/www/html/getImage/
# mkdir -p /var/www/html/getImage/images/

创建 index.php文件,
包含以下内容。

<?php

$url = str_replace('index.php','', $_SERVER['PHP_SELF']);
$url = str_replace($url,'',$_SERVER['REQUEST_URI']);
$url = explode('/',$url);
$name = array_shift($url);
$weburl = array_shift($url);

$command = "/usr/bin/wkhtmltoimage --no-images --load-error-handling ignore";
$dir_img = "/var/www/html/getImage/images/";     // Image files will be saved here
$ex_cmd = "$command $weburl " . $dir_img . $name;
$output = shell_exec($ex_cmd);
echo "<img src="/getImage/images/$name" >";  // comment this to disable image show on page

?>

确保所有目录路径正确,

现在创建一个 .htaccess
将所有请求移动到index.php文件中。
确保服务器启用了.htaccess文件。

# vi /var/www/html/getImage/.htaccess

RewriteEngine On
RewriteCond %{REQUEST_URI} /images/.+(gif|png|jpg)$
RewriteRule .* - [L]
RewriteRule ^.*$ index.php

现在我们可以通过访问下面的url来创建图像
语法:

http://youdomain.com/getImage/[imagename]/[site url without http prefix]

例子:

https://theitroad.com/getImage/123.jpg/yahoo.com