javascript - Concat 缓冲区或替代方法

标签 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 将以 block 的形式传送,我需要组合缓冲区并在最后使用 Sharp 将图像转换为另一种大小:

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

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

最佳答案

您可以使用 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);

关于javascript - Concat 缓冲区或替代方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46979764/

相关文章:

Javascript DOM : Pinpointing "input" elements by their type?

javascript - React JS 未捕获引用错误 : require is not defined

node.js - 如何使用 socket.io 和 cryptojs 以及 sql server 结果发出对象数组?

json - NodeJS JSON 文件读取时不带换行符

node.js - 嵌入模式给出错误

javascript - 如何将 HTTP header 发送到 Connect (Node.js) 中的静态目录

javascript - 类内部的bind()与 "classic"对象内部的bind

javascript - 如何在javascript中同时调用函数?

node.js - 如何将一个模板的一些数据发送到另一个模板 Meteor

javascript - 如何正确处理 Express 中的错误?