shell指令碼擷取網頁快照並產生縮圖

來源:互聯網
上載者:User

標籤:des   style   blog   http   io   color   ar   os   使用   

擷取網頁快照並產生縮圖可分兩步進行:

1、擷取網頁快照

2、產生縮圖

擷取網頁快照

這裡我們用 phantomjs 來實現。關於 phantomjs 的詳細用法可參考官方網站。

1、安裝

我的環境是CentOS6.5,安裝時直接下載 tarball 然後解壓即可。

# wget https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-1.9.8-linux-i686.tar.bz2# tar -jxvf phantomjs-1.9.8-linux-i686.tar.bz2# cp phantomjs-1.9.8-linux-i686/bin/phantomjs /bin/phantomjs

第二步中解壓後bin目錄下的 phantomjs 二進位檔案即是可調用命令。

第三步是為了在以後調用命令時不必輸入命令全路徑。

2、調用

phantomjs的調用需要一個js指令碼。這個js指令碼接收兩個參數,分別是網址url和快照檔案名稱filename,指令碼snap.js內容如下:

/* * desc: get snapshot from url * author: 十年後的盧哥哥(http://www.cnblogs.com/lurenjiashuo/) * example: phantomjs snap.js http://www.baidu.com baidu.png */var page = require(‘webpage‘).create();var args = require(‘system‘).args;var pageW = 1024;var pageH = 768;page.viewportSize = {  width: pageW,  height: pageH};var url =  args[1];var filename = args[2];page.open(url, function (status) {    if (status !== ‘success‘) {        console.log(‘Unable to load ‘ + url + ‘ !‘);        phantom.exit();    } else {        window.setTimeout(function () {            page.clipRect = { left: 0, top: 0, width: pageW, height: pageH };            page.render(filename);            console.log(‘finish:‘, filename);            phantom.exit();        }, 1000);    }});

在這個指令碼中還有個小小的設定,就是設定開啟頁面的瀏覽器可視地區的大小為1024*768,然後取第一屏內容。

調用命令如下:

phantomjs snap.js http://www.baidu.com baidu.png

注意:這裡執行命令的使用者需要對目錄有寫入權限。

3、效果

擷取的如下:

產生縮圖

產生縮圖用的是ImageMagick工具,ImageMagick是個非常強大的圖片處理工具,可對圖片進行轉化(格式轉換、縮放、剪下、模糊、反轉等)、螢幕、圖片顯示等,詳細用法可參考  我的ImageMagick使用心得 一文。

1、安裝

redhat系列可使用yum安裝:

# yum install ImageMagick ImageMagick-devel

其他平台安裝請參考官方網站:http://www.imagemagick.org/script/binary-releases.php,根據你的系統選擇相應的包或自己編譯源碼。

2、調用

我們這裡只使用圖片縮放工具,文法為:

convert -resize 320x240 baidu.png baidu_thumbnail.png
3、效果

產生的縮圖如下:

 

整合指令碼

如果希望將上兩步自動化,可以寫一個shell指令碼實現:

# !/bin/bash# desc: create snapshot from url# autor: 十年後的盧哥哥(http://www.cnblogs.com/lurenjiashuo/)# example: sh createsnap.sh http://www.baidu.com baiduURL=$1IMAGE_NAME=$2SNAPSHOT_NAME="${IMAGE_NAME}.png"THUMBNAIL_NAME="${IMAGE_NAME}_thumbnail.png"phantomjs snap.js $URL $SNAPSHOT_NAMEconvert -resize 320x240 $SNAPSHOT_NAME $THUMBNAIL_NAMEexit 0
參考文檔

1、http://phantomjs.org/

2、http://www.imagemagick.org/

shell指令碼擷取網頁快照並產生縮圖

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.