Create Website Thumbnails using PhantomJS


Hits: 9231  

Hope you read my old article “Create WebThumb using LAMP”, it used for creating web thumbnails from Xvfb virtual framebuffer that is more time and resource consuming.

Shell Script with Xvfb try to open web browsers in real remote server to capture web-thumbs…

That whole setup might take a full day and image quality is very bad….

Thanks to PhantomJS

PhantomJS is a headless WebKit with JavaScript API. It has fast and native support for various web standards: DOM handling, CSS selector, JSON, Canvas, and SVG.

Simple Javascript example

console.log(‘Loading a web page’);
var page = require(‘webpage’).create();
var url = ‘http://www.svnlabs.com/’;
page.open(url, function (status) {
//Page is loaded!
phantom.exit();
});

Features:

– Headless Website Testing
– Screen Capture
– Page Automation
– Network Monitoring

Fork on Github https://github.com/ariya/phantomjs

PhantomJS is using WebKit for a real layout and rendering engine, it can be used to capture web page as screenshot or PDF files. PhantomJS can render anything on the web page, it can be used to convert contents in HTML/CSS, SVG and Canvas.

URL2PNG-URL2PDF-HTML2JPG-URL2IMAGE
URL2PNG-URL2PDF-HTML2JPG-URL2IMAGE
// Thumbnail of Webpage using webthumb.js

var page = require('webpage').create(),
    system = require('system'),
    weblink,
    fname;

if (system.args.length !== 3) {
    console.log('Usage: webthumb.js webURL filename');
    console.log('Usage: webthumb.js http://www.svnlabs.com svnlabs.png');
    phantom.exit(1);
} else {
    weblink = system.args[1];
    fname = system.args[2];    
    page.viewportSize = { width: 320, height: 480 };
    page.open(weblink, function (status) {
    if (status !== 'success') {
        console.log('Unable to open webpage!');
    } else {
        page.render(fname);
    }
    window.setTimeout(function () {
      phantom.exit();
    }, 3000);
    });
}

Download webthumb.js

# phantomjs webthumb.js http://www.svnlabs.com svnlabs.png
# phantomjs webthumb.js http://www.svnlabs.com svnlabs.pdf

You can even capture webpage as good quality PDF file 😉

Output:

svnlabs.png
svnlabs.pdf

You can also use examples/rasterize.js for same sort of functions 😉

# phantomjs examples/rasterize.js http://www.svnlabs.com/ svnlabs.png
# phantomjs examples/rasterize.js ‘http://www.svnlabs.com/’ svnlabs.pdf

rasterize.js – rasterizes a web page to image or PDF
render_multi_url.js – renders multiple web pages to images
technews.js – captures Google News as a PNG image