使用PhantomJS可以捕获网页屏幕而不将其保存到文件系统中吗?

我需要这样做是因为我想对页面截图进行一些后期处理(配色方案检测)。

颜色检测也使用JS。(https://github.com/leeoniya/RgbQuant.js)进行,并且可以处理HTMLImageElementHTMLCanvasElementImageDataCanvasRenderingContext2D

这是PhantomJS API,但是render方法仅支持文件路径:http://phantomjs.org/screen-capture.html

最佳答案

感谢Artjom B.在评论中为您提供的解决方案。工作正常。
首先,我创建了页面的屏幕截图,并将其保存到文件夹screenshots,其中的html file包含此屏幕截图。

page.open(url, function (status) {
    // Make screenshot and save it to './screenshots'
    var rel_path = 'screenshots/' + btoa(url) + '_' + (new Date().getTime());

    // Image path
    var img_path = rel_path + '.png';

    // HTML page path
    var html_path = rel_path + '.html';

    // Make screenshot
    page.render(img_path);

    // Create webpage with the image, but take the absolute path.
    fs.write(html_path, '<html><body><img id="image" src="' + 'file:///' + fs.absolute(img_path) + '"/></body></html>', 'w');
});


之后,我再次用幻像打开了创建的文件。通过id = image加载图像并执行我的RGB量化。

p.open('file:///' + html_path, function start(status) {
    console.log('[RGB-QUANTIFICATION]: ' + self.url);

    // Inject image quantification library
    p.injectJs('ext/rgbquant.js');

    // Generate color palette
    var colors = p.evaluate(function () {
        var rgb_quant_settings = {colors: 5, method: 2, initColors: 4096, minHueCols: 0};
        var rgb_quant = new RgbQuant(rgb_quant_settings);
        rgb_quant.sample(document.getElementById('image'));
        return rgb_quant.palette(true);
    });

    ...

});

10-04 22:45
查看更多