PHP+PhantomJS实现网页截图

  • 2021年4月26日
  • 技术
之前有个业务需求是前台会再本地递交数据到服务器,然后服务器根据前台的数据生成图片,并且提供图片链接返回,于是这里就需要后端生成图片,便用到了PhantomJS.

hantomJS俗称为:无界面的浏览器。PhantomJS是一个基于webkit的JavaScript API。它使用QtWebKit作为它核心浏览器的功能,使用webkit来编译解释执行JavaScript代码。任何你可以在基于webkit浏览器做的事情。

说人话就是网页无论是数据渲染生成的,或者是静态化的,还是说需要执行js的,它在后端都可以执行。当然这只是一个狭义的理解,更详细的还需要更深入研究。

首先,安装PhantomJS,用的是Ubuntu 16,安装的是phantomjs-2.1.1版本

 #下载phantomjs-2.1.1版本
 wget https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-linux-x86_64.tar.bz2

 #解压文件
 tar -xvf phantomjs-2.1.1-linux-x86_64.tar.bz2

 #将文件移动到指定目录(方便管理)
 mv phantomjs-2.1.1-linux-x86_64 /usr/lib/phantomjs/

 #建立软连接
 sudo ln -sf /usr/lib/phantomjs/bin/phantomjs  /usr/local/bin/phantomjs

操作完成后执行 phantomjs –version 查看版本号,返回的相应的版本号便完成了安装

root@fionasit:~# phantomjs --version
2.1.1

然后,先截一张图测试一下

root@fionasit:~# phantomjs snapshot.js  https://www.baidu.com/  1.png
root@fionasit:~#

这里的意思是使用snapshot.js脚本处理一个url链接(百度首页)并且生成图片文件1.png

snapshot.js代码内容:

var page = require('webpage').create(),
    system = require('system'),
    address, filename;

//参数判断
if (system.args.length !== 3) {
    console.log('Usage: snapshot.js <some URL> <Filename>');
    phantom.exit();
}

//获取参数
address = system.args[1];  //https://www.baidu.com/
filename = system.args[2]; //1.png

page.open(address, function (status) {
    if (status !== 'success') {
        console.log('FAIL to load the address');
    } else {
        page.evaluate(function() {
            document.body.bgColor = 'white';
        });
        //这里使用定时器是因为有的网页加载需要时间
        window.setTimeout(function () {
            page.render(filename,{format:'jpeg',quality:'100'});
            page.close();
            phantom.exit();
        }, 3000);
    }
});

注意:这里生成图片后有可能因为系统字体的关系,导致图片文字显示有问题:

安装字体就行了

root@fionasit:~# apt-get install xfonts-wqy
root@fionasit:~#

最后,在php中执行,需要开启php的exec函数

$SavePath = '1.png';
$JsPath = 'snapshot.js';
$Url = "https://www.baidu.com/";
$command = "phantomjs {$JsPath}  {$Url}  {$SavePath}";
exec($command);
if(!file_exists($SavePath)){
  echo "error";
}else{
  echo "success";
}

完成!

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注