<?php
namespace
weapp\library\phantomjs;
use
weapp\library\BizException;
class
ScreenShot
{
private
$js_path
;
private
$temp_dir
;
function
__construct()
{
$dir
= __DIR__;
$this
->js_path =
"{$dir}/script.js"
;
$this
->temp_dir = \Yii::getAlias(
'@runtime'
);
}
public
function
screenShotThenSaveToOss(string
$url
, string
$filename
=
'temp.jpg'
)
{
$outputFilePath
=
"{$this->temp_dir}/$filename"
;
$cmd
=
"\usr\local\bin\phantomjs {$this->js_path} '$url' '$outputFilePath'"
;
exec
(
$cmd
,
$output
);
$isShotImgaeExist
=
file_exists
(
$outputFilePath
);
if
(!
$isShotImgaeExist
) {
throw
new
BizException(0,
'phantomjs截图失败'
, BizException::SELF_DEFINE);
}
$result
=
$this
->postScreenShotImageToOss(
$outputFilePath
);
unlink(
$outputFilePath
);
return
$result
;
}
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();
curl_setopt(
$ch
, CURLOPT_URL,
$url
);
curl_setopt(
$ch
, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt(
$ch
, CURLOPT_POST, 1);
curl_setopt(
$ch
, CURLOPT_SAFE_UPLOAD, true);
curl_setopt(
$ch
, CURLOPT_POSTFIELDS,
$postData
);
curl_setopt(
$ch
, CURLOPT_RETURNTRANSFER, true);
curl_setopt(
$ch
, CURLOPT_TIMEOUT, 20);
curl_setopt(
$ch
, CURLOPT_CONNECTTIMEOUT, 20);
$res
= curl_exec(
$ch
);
$res
= json_decode(
$res
);
curl_close(
$ch
);
if
(
empty
(
$res
) ||
$res
->code != 0) {
return
''
;
}
else
{
return
$res
->data->url;
}
}
public
function
getOssPolicyToken(
$url
= null)
{
$url
= \Yii::
$app
->params[
'oss_screen_shot_token_api'
];
$ch
= curl_init();
curl_setopt(
$ch
, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt(
$ch
, CURLOPT_RETURNTRANSFER, true);
curl_setopt(
$ch
, CURLOPT_URL,
$url
);
$result
= curl_exec(
$ch
);
curl_close(
$ch
);
$res
= json_decode(
$result
);
if
(
empty
(
$res
) ||
$res
->code != 0) {
return
[];
}
else
{
return
$res
->data;
}
}
}