Sharp: store an image 2 times

Created on 15 Nov 2018  路  2Comments  路  Source: lovell/sharp

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
question

Most helpful comment

.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.

All 2 comments

.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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

terbooter picture terbooter  路  3Comments

jaekunchoi picture jaekunchoi  路  3Comments

jaydenseric picture jaydenseric  路  3Comments

natural-law picture natural-law  路  3Comments

zilions picture zilions  路  3Comments