phpphantom.js を使ってみたが、
背景をすべて白にする
背景が透明な場合は黒にする
のどちらかになってしまう。
また、細かいところに手がとどかない。
ということで、今回は phantom.js を php から使って
背景色が 透明なら 白にしてスクリーンショットを取得します。
・まずはキャプチャスクリプト
sc.js
var system = require('system');
var args = system.args;
var url = args[1] ;//argsは 1から始める
//console.log('dousa');
var page = require("webpage").create();
//ブラウザサイズ
page.viewportSize = {width: 1200, height: 1200};
page.open(url, function(status) {
//背景色を調べて、透明なら白にする。
page.evaluate(function() {
if (getComputedStyle(document.documentElement, null).backgroundColor === 'rgba(0, 0, 0, 0)') {
console.log('document.documentElement backgroundColor is transparent, setting color to white');
var style = document.createElement('style'),
text = document.createTextNode('body { background: #fff }');
style.setAttribute('type', 'text/css');
style.appendChild(text);
document.documentElement.insertBefore(style, document.documentElement.firstChild);
}
});
//任意のファイル名で保存。 絶対パスにしておかないとphpで保存時バグるので注意
if (status === "success") {
page.render("/var/www/html/sately.net/webroot/img/nira.png");
}
phantom.exit();
});
で、コマンドラインから
/var/www/html/yourdir/bin/phantomjs /var/www/html/yourdir/webroot/img/sc.js "http://yahoo.co.jp"
これでスクリーンショットが nira.png として保存される。
これをphp から動かす場合は
$cmd = '/var/www/html/sately.net/bin/phantomjs /var/www/html/sately.net/webroot/img/sc.js "http://google.co.jp"';
exec($cmd.' 2>&1', $output);
さらに permission denied が出る場合は、
パスを /var/www/ の代わりに /home/hideki/ みたいな感じで home から指定すると
permission エラーになるので注意すること。