I have to resize an image 2 times and store it in different files
and most importantly i want them to be Promise based so i can await them
currently i use this method which i doubt to be correct:
await sharp(my_file)
.jpeg({quality: 90, chromaSubsampling: '4:4:4'})
.resize(200, 200)
.toFile('200x200.jpg', (err, info) => {}); // save
await sharp(my_file)
.jpeg({quality: 90, chromaSubsampling: '4:4:4'})
.resize(40, 40)
.toFile('40x40.jpg', (err, info) => {}); // save
.toFile returns a Promise when a callback isn't specified.
If you want to encode the two different varieties in parallel, you can just do the following:
async function encode(my_file) {
const src = sharp(my_file).jpeg({quality: 90, chromaSubsampling: "4:4:4"});
const i200 = src.resize(200, 200).toFile("200x200.jpg");
const i40 = src.resize(40, 40).toFile("40x40.jpg");
return Promise.all([i200, i40]);
}
You can also await Promise.all([i200, i40]) in the above example, naturally, if you want it as part of a bigger function or pipeline.
Great! So I can use it like this:
await encode(my_file);
Perfect! many thanks.
Most helpful comment
.toFilereturns a Promise when a callback isn't specified.If you want to encode the two different varieties in parallel, you can just do the following:
You can also
await Promise.all([i200, i40])in the above example, naturally, if you want it as part of a bigger function or pipeline.