xcodejs
xcodejs

Reputation: 23

Concat Buffers or alternative method

I want to resize image screenshot of webshot module without touching disk, doing all in memory.

Here is what I have

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;});

Since the data will be delivered in chunks, I need to combine Buffers and at the end convert the image to another size using Sharp:

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

But I just can't concat buffers and not sure how to do it directly with Sharp without concatenating buffers. Any ideas how to do it properly?

Upvotes: 2

Views: 304

Answers (1)

ufxmeng
ufxmeng

Reputation: 2600

You can use pipe to resize your image.

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);

Upvotes: 1

Related Questions