phantomjs截取網頁截圖
場景
有一個視頻播放地址,需要對該網頁進行截圖
解決思路:
1.將視頻下載到本地,使用ffmpeg進行處理
2.使用phantomjs,phantomjs內置了webkit瀏覽器引擎,phantomjs可以模擬瀏覽器打開視頻地址,然后進行整個網頁的截圖。
WebKit 是一個開源的瀏覽器引擎,與之相對應的引擎有Gecko(Mozilla Firefox 等使用)和Trident(也稱MSHTML,IE 使用)
選擇
第一個方案,ffmpeg只能處理本地視頻或者處理RTCP直播流,同時要求的視頻直播地址中有部分是直播流,有部分是組件渲染,所以該方案不可行。
因此選擇第二個方案。
phantomjs進行網頁截圖,這里以window平臺為例
1.首先,去phantomjs官網下載頁面下載phantomjs程序,支持window、mac os、linux、freebsd平臺。
2.將下載下來的phantomjs添加系統(tǒng)環(huán)境變量里
3.編寫js文件capture.js
"use strict"; //嚴格模式
var page = require('webpage').create();
var system = require('system');
page.viewportSize = {
width : 1024,
height : 720
};
if (system.args.length < 3) {
console.log('param must greater 2');
phantom.exit();
} else{
var url = system.args[1]; //遠程視頻地址
var saveFile = system.args[2]; //保存截圖的文件路徑
page.open(url, function(status) {
if (status == 'success'){
// 通過在JS獲取頁面的渲染高度
var rect = page.evaluate(function () {
return document.getElementsByTagName('html')[0].getBoundingClientRect();
});
// 按照實際頁面的高度,設定渲染的寬高
page.clipRect = {
top: rect.top,
left: rect.left,
width: rect.width,
height: rect.height
};
setTimeout(function() {
var result = page.render(saveFile);
page.close();
console.log(result);
phantom.exit();
}, 1000); //延遲截圖時間
}
})
}
4.在php中進行調用
$url = 'http://xxx';
$savePath = 'c:\test.png';
$jsPath = 'c:\phantomjs.js';
$command = "phantomjs {$jsPath} {$url} {$savePath}";
$result = @exec($command );
這樣就對網頁進行截圖,保存截圖在指定路徑中。
另外:有大神在github上提交了個操作phantomjs的php類庫,可以參考使用:
https://github.com/jonnnnyw/php-phantomjs
http://jonnnnyw.github.io/php-phantomjs/4.0/2-installation/
————————————————
版權聲明:本文為CSDN博主「陪代碼一起浪跡天涯」的原創(chuàng)文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/seoyundu/article/details/101782923