PHP網頁截取快照:PHP截取網站網頁保存爲一張圖片實現。

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添加系統環境變量裏
    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/

參考自:
http://phantomjs.org/download.html
http://phantomjs.org/api/webpage/method/render.html

代碼實例:

phantomjs和slimerjs,兩款都是服務器端的js,簡單說來,都是封裝了瀏覽器解析引擎,不同是phantomjs封裝的 webkti,slimerjs封裝的是Gecko(firefox)。 權衡利弊,決定研究下phantomjs,於是就用phantomjs實現了網 站快照生成。phantomjs的項目地址是:http://phantomjs.org/

代碼涉及兩個部分,一個是設計業務的index.php,另一個是生成快照的js腳本snapshot.js。代碼比較簡單,僅僅是實現了功能,沒有做過多的修飾。代碼分別如下所示:

php:

<?php
    if (isset($_GET['url']))
    {
       set_time_limit(0);

       $url = trim($_GET['url']);
       $filePath = "./cache/".md5($url).'.png';

       if (is_file($filePath))
       {
           exit($filePath);
       }

       $command = "phantomjs/bin/phantomjs snapshot.js {$url} {$filePath}";
       exec($command);

       exit($filePath);
    }
?>

html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="keywords" content="" />
<meta name="description" content="" />
<title>快照生成</title>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<style>
* {
    margin: 0;
    padding: 0;
}

form {
    padding: 20px;
}

div {
    margin: 20px 0 0;
}

input {
    width: 200px;
    padding: 4px 2px;
}

#placeholder {
    display: none;
}
</style>
</head>

<body>
   <form action="" id="form">
       <input type="text" id="url" />
       <button type="submit">生成快照</button>

       <div>
           <img src="" alt="" id="placeholder" />
       </div>
   </form>

   <script>
   $(function(){
       $('#form').submit(function(){
           if (typeof($(this).data('generate')) !== 'undefined' && $(this).data('generate') === true)
           {
               alert('正在生成網站快照,請耐心等待...');
               return false;
           }

           $(this).data('generate', true);
           $('button').text('正在生成快照...').attr('disabled', true);

           $.ajax({
               type: 'GET',
               url: '?',
               data: 'url=' + $('#url').val(),
               success: function(data){
                   $('#placeholder').attr('src', data).show();
                   $('#form').data('generate', false);
                   $('button').text('生成快照').attr('disabled', false);
               }
           });

           return false;
       });
    });
   </script>
</body>
</html>

php利用CutyCapt實現網頁高清截圖 :

     網頁截圖功能,必須安裝IE+CutyCapturl:要截圖的網頁out:圖片保存路徑path:CutyCapt路徑cmd:CutyCapt執行命令比如:http://你php路徑.php?url=http://XX.com

 

<?php
/* 
網頁截圖功能,必須安裝IE+CutyCapt
url:要截圖的網頁
out:圖片保存路徑
path:CutyCapt路徑
cmd:CutyCapt執行命令
比如:http://你php路徑.php?url=http://niutuku9.com/
*/
$url=$_GET["url"];
$imgname=str_replace('http://','',$url);
$imgname=str_replace('https://','',$imgname);
$imgname=str_replace('.','-',$imgname);
$out = 'D:/webroot/test/'.$imgname.'.png';
$path = 'D:/webserver/CutyCapt.exe';
$cmd = "$path --url=$url --out=$out";
echo $cmd;
system($cmd);
?>
CutyCapt下載地址:http://sourceforge.net/projects/cutycapt/files/cutycapt/

windows的不用安裝的,直接下載解壓放到相對應的路徑即可

linux安裝CutyCapt教程:http://niutuku9.com/tech/php/273578.shtml

整理參考來自:軟盟網

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章