Chris
Chris

Reputation: 4364

Resize one image multiple times

I am resizing a given image (saved on disk) to different sizes:

var image = 'photos/pic';
var sizes = [1440, 1080, 720, 480];

for (var i = 0; i < sizes.length; i++) {
    sharp(image + '.jpg')
    .resize(sizes[i], sizes[i])
    .toFile(image + '-' + sizes[i] + '.jpg');       
}

This works as expected, but I guess there is room for improvements.

Upvotes: 6

Views: 3989

Answers (2)

Fadi Abo Msalam
Fadi Abo Msalam

Reputation: 7197

you can do it by using bluebird promise

const Promise = require('bluebird');
global.Promise = Promise;


var sizes = [{
path: 'large',
xy: 800
},{
    path: 'medium',
    xy: 300
},{
    path: 'small',
    xy: 100
}];
Promise.map(sizes, function(size) {
    return sharp( img.buffer )
        .resize( size.xy, size.xy )
        .toFile( size.path );
});

src :- https://github.com/lovell/sharp/issues/154

i tried it and it is working 100%

Upvotes: 1

Ian Warner
Ian Warner

Reputation: 1068

You can use the Clone method for Sharp JS

http://sharp.dimens.io/en/stable/api-input/#clone

The example gives it all you need

// Create the baseline changes
const pipeline = sharp().rotate();

pipeline.clone().resize(800, 600).pipe(firstWritableStream);
pipeline.clone().extract({ left: 20, top: 20, width: 100, height: 100 
  }).pipe(secondWritableStream);

readableStream.pipe(pipeline);

Can also use this with promises

Upvotes: 0

Related Questions