Resize one image multiple times
Asked Answered
H

2

6

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.

  • Will the for-loop lead to any problems? If yes, is there a better way to solve that?
  • Would it be faster to wait for the generated picture to be resized and use this for the next resizing process? Let's say the original picture is 2000x2000. What's the speed improvement from resizing 720x720 to 480x480 instead of 2000x2000 to 480x480, if there is any? Considering I have to read the 720x720 file first and wait for the resizing to be finished.
  • Should I do those resizes on the "main" node thread or fork a child process? They are running asynchronously anyways, correct?
Hendricks answered 30/4, 2017 at 8:32 Comment(3)
i am just gonna give basic comments :- first cache the sizes.length since we don't need to access it 4 times like this :- var length=sizes.length; var tempSize; for(vari=0;i<length;i++){ tempsize=sizes[i] // here the sizes[i] will be accessed once instead of three times }Ashford
regarding your third point what library are you using ? how did you assume it is asynchronously ? the resizing from first look seems sync ... if it was async as you says of course it will cause you problems since forloop will be finished before the resizing thus it will mare 4 copies of 1440 pixel ... do you get me ?Ashford
sharp, see tags.Hendricks
A
1

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%

Ashford answered 11/12, 2017 at 19:32 Comment(0)
S
0

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

Somewhere answered 6/12, 2017 at 15:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.