php如何调用phantomJS截图

php如何调用phantomJS截图

php调用phantomJS截图

  • 知识储备

*unix系统安装phantomjs,权限相关知识

基本JavaScript语法知识

php exec函数调用REPL phantomjs

phantomjs js截图文档 http://javascript.ruanyifeng.com/tool/phantomjs.html

  • 代码(php 代码环境为yii2框架)

<?php
namespace weapp\\library\\phantomjs;
use weapp\\library\\BizException;
class ScreenShot
{
    /** @var string 获取phantomjs 参数中 js文件的决定路径 */
    private $js_path;
    /** @var bool|string 获取php 有777权限的临时文件目录 */
    private $temp_dir;
    function __construct()
    {
        $dir = __DIR__;
        $this->js_path = "{$dir}/script.js";
        /** @var bool|string 获取php 有777权限的临时文件目录 */
        $this->temp_dir = \\Yii::getAlias('@runtime');
    }
    /**
     * 截图并上传
     * @param string $url
     * @param string $filename
     * @return string
     * @throws BizException
     */
    public function screenShotThenSaveToOss(string $url, string $filename = 'temp.jpg')
    {
        //输出图片的路径
        $outputFilePath = "{$this->temp_dir}/$filename";
        //执行的phantomjs命令
        //phantomjs 可执行文件必须是 绝对路径 否则导致 exec 函数返回值127错误
        $cmd = "\\usr\\local\\bin\\phantomjs {$this->js_path} '$url' '$outputFilePath'";
        //捕捉不到phantomjs命令输出结果
        exec($cmd, $output);
        //检查截图文件是否存在
        $isShotImgaeExist = file_exists($outputFilePath);
        if (!$isShotImgaeExist) {
            throw new BizException(0, 'phantomjs截图失败', BizException::SELF_DEFINE);
        }
        //保存截图到oss
        $result = $this->postScreenShotImageToOss($outputFilePath);
        //删除临时文件夹的截图图片
        unlink($outputFilePath);
        return $result;
    }
    /**
     * 上传截图到阿里云直传oss
     * @param string $screenshot_path
     * @return string
     */
    public function postScreenShotImageToOss(string $screenshot_path): string
    {
        $ossKey = 'raw_file_name';
        $file = new \\CURLFile($screenshot_path, 'image/jpeg', 'file');
        $tokenArray = $this->getOssPolicyToken('fetch');
        $url = $tokenArray->host;
        $postData = [
            'key' => "{$tokenArray->dir}/$ossKey",
            'policy' => $tokenArray->policy,
            'OSSAccessKeyId' => $tokenArray->accessid,
            'success_action_status' => '200',
            'signature' => $tokenArray->signature,
            'callback' => $tokenArray->callback,
            'file' => $file
        ];
        $ch = curl_init();
        //$data = array('name' => 'Foo', 'file' => '@/home/user/test.png');
        curl_setopt($ch, CURLOPT_URL, $url);
        // Disable SSL verification
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true); // required as of PHP 5.6.0
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 20);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
        //curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: $mime_type"]);
        $res = curl_exec($ch);
        $res = json_decode($res);
        curl_close($ch);
        if (empty($res) || $res->code != 0) {
            return '';
        } else {
            return $res->data->url;
        }
    }
    /**
     * 调用管理后台阿里云oss token接口
     * @param null $url
     * @return array
     */
    public function getOssPolicyToken($url = null)
    {
        $url = \\Yii::$app->params['oss_screen_shot_token_api'];
        $ch = curl_init();
        // Disable SSL verification
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        // Will return the response, if false it print the response
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // Set the url
        curl_setopt($ch, CURLOPT_URL, $url);
        // Execute
        $result = curl_exec($ch);
        // Closing
        curl_close($ch);
        $res = json_decode($result);
        if (empty($res) || $res->code != 0) {
            return [];
        } else {
            return $res->data;
        }
    }
}
phantomjs javascript脚本内容
"use strict";
var system = require('system');
var webPage = require('webpage');
var page = webPage.create();
//设置phantomjs的浏览器user-agent
page.settings.userAgent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1';
//获取php exec 函数的命令行参数
if (system.args.length !== 3) {
    console.log(system.args);
    console.log('参数错误');
    console.log('第2个参数为url地址 第3个参数为截图文件名称');
    phantom.exit(1);
}
//命令行 截图网址参数
var url = system.args[1];
//图片输出路径
var filePath = system.args[2];
console.log('-------');
console.log(url);
console.log('-------');
console.log(filePath);
console.log('-------');
//设置浏览器视口
page.viewportSize = {width: 480, height: 960};
//打开网址
page.open(url, function start(status) {
    //1000ms之后开始截图
    setTimeout(function () {
        //截图格式为jpg 80%的图片质量
        page.render(filePath, {format: 'jpg', quality: '80'});
        console.log('success');
        //退出phantomjs 避免phantomjs导致内存泄露
        phantom.exit();
    }, 1000);
});

关于php如何调用phantomJS截图的文章就分享到这,如果对你有帮助欢迎继续关注我们哦

本文来自投稿,不代表重蔚自留地立场,如若转载,请注明出处https://www.cwhello.com/41821.html

如有侵犯您的合法权益请发邮件951076433@qq.com联系删除

(0)
php学习php学习订阅用户
上一篇 2022年6月23日 16:31
下一篇 2022年6月23日 16:31

相关推荐

  • php构造函数的小结

    构造函数的小结 类定义的进一步完善

    2018年4月11日
    0185
  • PHP入门指南:字符串。

    PHP是一种广泛使用的服务器端脚本语言,它强大的字符串处理功能是其受欢迎的原因之一。本文将介绍PHP字符串的基础知识以及常见的字符串操作。 什么是字符串? 在计算机编程中,字符串是由一系列字符组成的数据类型…

    2023年5月22日
    00
  • PHP实现MongoDB数据库分片的方法。

    随着数据量的增加,单个MongoDB实例的存储和处理能力可能会受到限制,导致性能下降。为了更好地处理大量数据,MongoDB提供了分片的功能,在多个服务器上分散数据以提高性能和可用性。PHP作为一种常用的Web编程语言…

    2023年5月21日
    02
  • PHP微信分享功能开发(附代码)

    有时候当一个项目或工程需要微信端分享之后做一系列事件那么我们就需要获取到微信分享这个动作,也就是说我们已经知道了当前这个东西已经被分享了 ,那么走微信默认的分享显然是不行的我们需要自己动手来配置微信分…

    2018年3月9日
    0245
  • 如何在PHP-MVC框架中使用RESTful风格的API。

    随着互联网应用的迅猛发展,越来越多的应用需要提供RESTful风格的API接口。而PHP-MVC框架也成为了现在Web开发中最常用的框架之一。那么,如何在PHP-MVC框架中使用RESTful风格的API呢? 一、什么是RESTful API? 首…

    2023年6月3日
    05
  • PHP中使用PDO操作事务的一些小测试

    PHP中使用PDO操作事务的一些小测试关于事务的问题,我们就不多解释了,以后在学习 MySQL 的相关内容时再深入的了解。今天我们主要是对 PDO 中操作事务的一些小测试,或许能发现一些比较好玩的内容。 在 MyISAM 上使…

    2023年3月29日
    00
  • PHP实现MySQL主从复制自动切换的方法。

    在现代化的应用架构中,数据库是至关重要的一环,对于高负载和高可用性应用,MySQL主从复制架构是广泛采用的一种解决方案。但是在MySQL主从复制模型下,主节点发生故障后需要手动切换从节点为主节点,这不仅会造成…

    2023年5月21日
    05
  • 谈谈PHP中的 ->、=> 和 :: 符号

    本篇文章给大家介绍一下php新手经常碰到的问题,->、=> 和 :: 这三个家伙是什么分别都是做什么的啊!看着就很晕。 没关系,下面我们做一下详细的解释,如果你有C++,Perl基础,你会发现这些家伙和他们里面的一…

    2022年6月11日
    0182

联系我们

QQ:951076433

在线咨询:点击这里给我发消息邮件:951076433@qq.com工作时间:周一至周五,9:30-18:30,节假日休息