Concat Buffers或替代方法

时间:2017-10-27 16:36:54

标签: javascript node.js express

我希望在不触及磁盘的情况下调整webshot模块的图像屏幕截图,在内存中完成所有操作。

这就是我所拥有的

var webshot = require('webshot');
var fs      = require('fs');
var sharp = require('sharp');

alldata = new Buffer(1024*1024);

var options= {
windowSize: {
    width: 1024
  , height: 768
},
zoomFactor:0.25,
renderDelay:500,
quality:50,
phantomConfig: {'ignore-ssl-errors': 'true'}
};

var file = fs.createWriteStream('google.png', {encoding: 'binary'});
var renderStream = webshot('google.com', options);

var completed = false;

renderStream.on('data', function(data) {
    console.log(Type(data));
    alldata.write(data);
});

renderStream.on('end', function(data) {
    completed=true;
});

require('deasync').loopWhile(function(){return !completed;});

由于data将以块的形式传递,我需要将Buffers组合在一起,最后使用Sharp将图像转换为另一个尺寸:

var resizeTransform = sharp(thebuffer).resize(320, 270).max();

但我无法连接缓冲区,也不确定如何在不连接缓冲区的情况下直接使用Sharp。任何想法如何正确地做到这一点?

1 个答案:

答案 0 :(得分:1)

您可以使用pipe调整图片大小。

var webshot = require('webshot');
var fs = require('fs');
var sharp = require('sharp');

var options = {
    windowSize: {
        width: 1024,
        height: 768
    },
    zoomFactor: 0.25,
    renderDelay: 500,
    quality: 50,
    phantomConfig: { 'ignore-ssl-errors': 'true' }
};

var file = fs.createWriteStream('google.png', { encoding: 'binary' });
var renderStream = webshot('google.com', options);
const resizeStream = sharp().resize(320, 270).png();
//pipe your stream, get the webshot, resize it, then save to png
renderStream.pipe(resizeStream).pipe(file);
//since res is a writable stream, you can pipe the stream down to it just like the file stream.
//renderStream.pipe(resizeStream).pipe(res);