寫截取整個網頁程序是一個作前臺的哥們所託,要作一些漂亮的界面原形,參考一些不錯的網站設計就幫他弄了個截屏的程序。css
phantomjs 是一個基於js的webkit內核無頭瀏覽器 也就是沒有顯示界面的瀏覽器,這樣訪問網頁就省去了瀏覽器的界面繪製所消耗的系統資源,比較適合用於網絡測試等應用 。我只是調用了其中的一個截取網頁的小功能,能夠完美的解析網頁的js和css 並且兼容html5,不過最新的1.5版本不支持flash,因此我採用了1.4的版本,可以獲得完整的網頁體驗。html
先看看執行的效率(4M電信,22:30點測試):html5
phantomjs的目錄結構 web
dll挺多的 都是必須的 codecs裏面包含編碼信息 qcncodecs4.dll 這個是中文支持 裏面還有韓文 日文和臺灣繁體中文 這玩意必須有 要否則會出現亂碼的。瀏覽器
imageformats目錄裏面是qgif4.dll和qjpeg4.dll兩個dll 是用於圖片轉換的 默認png格式。網絡
rasterize.js 就是官方寫好的截屏的js代碼多線程
var page = require('webpage').create(), address, output, size; if (phantom.args.length < 2 || phantom.args.length > 3) { console.log('Usage: rasterize.js URL filename [paperwidth*paperheight|paperformat]'); console.log(' paper (pdf output) examples: "5in*7.5in", "10cm*20cm", "A4", "Letter"'); phantom.exit(); } else { address = phantom.args[0]; output = phantom.args[1]; page.viewportSize = { width: 600, height: 600 }; if (phantom.args.length === 3 && phantom.args[1].substr(-4) === ".pdf") { size = phantom.args[2].split('*'); page.paperSize = size.length === 2 ? { width: size[0], height: size[1], border: '0px' } : { format: phantom.args[2], orientation: 'portrait', border: '1cm' }; } page.open(address, function (status) { if (status !== 'success') { console.log('Unable to load the address!'); } else { window.setTimeout(function () { page.render(output); phantom.exit(); }, 200); } }); }
看這個js的意思貌似能夠將pdf文件轉換爲圖片文件,我沒有測試。我調用的時候只是傳了兩個參數。less
下面的就算調用的核心js代碼 直接輸出圖像文件。測試
page.render(output);
在C#中調用這玩意的代碼是:網站
private void GetImage(string url) { string links = url.IndexOf("http://") > -1 ? url : "http://" + url; #region 啓動進程 Process p = new Process(); p.StartInfo.FileName = Environment.CurrentDirectory+"//phantomjs.exe"; p.StartInfo.WorkingDirectory = Environment.CurrentDirectory+"//pic//"; p.StartInfo.Arguments = string.Format("--ignore-ssl-errors=yes --load-plugins=yes " + Environment.CurrentDirectory + "//rasterize.js " + links + " "+url+".png"); p.StartInfo.CreateNoWindow = true; p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; if (!p.Start()) throw new Exception("沒法Headless瀏覽器."); #endregion }
關鍵是這裏
p.StartInfo.Arguments = string.Format("--ignore-ssl-errors=yes --load-plugins=yes " + Environment.CurrentDirectory + "//rasterize.js " + links + " "+url+".png");
--ignore-ssl-errors=yes 忽視加密的ssl鏈接錯誤
--load-plugins=yes 載入插件
上面的兩參數能夠不用 ,加上了是爲了體驗真實的網頁體驗效果,好比,不載入插件的話 flash就不會加載的。
Environment.CurrentDirectory + "//rasterize.js " 這裏就是調用寫好的js驅動代碼,下面帶上的參數是做用於這個js的。
links 訪問的網址鏈接,最好加入http://。
"+url+".png 輸出的圖片 默認是png格式 當包含了上面 imageformats裏面的dll的話 就能夠輸出jpg格式和gif格式的圖片。 全部代碼就這樣子的,用起來很簡單,就像在代碼中調用cmd同樣的。這樣就很容易在不錯的機子上進行多線程的批量截圖而不影響任何操做,效率方面還很不錯!
後面附上截取 www.sina.com 網站效果:
默認png的圖片 效果仍是很不錯的