Sharp: Convert image folder into webp

Created on 28 Apr 2020  路  1Comment  路  Source: lovell/sharp

What are you trying to achieve?
I am trying to convert the full images folder (all images inside are jpg png) into webp is it possible with sharp?

question

Most helpful comment

That's a perfect use case for sharp.

Here's a quick demo how to do it:

const fs = require('fs')
const sharp = require('sharp')

const files = fs.readdirSync('/tmp/images')

const convert = (dir, name) => {
  const fullname = dir + '/' + name
  const i = sharp(fs.readFileSync(fullname));
  i.toFormat('webp', { quality: 80 })
  return i.toFile('/tmp/converted-images/' + name + '.webp')
    .then(() => console.log('Converted', fullname))
    .catch(e => console.log('Failed converting', fullname, e, 'skipping...'))
}

const promises = files.map(name => convert('/tmp/images/', name))

Promise.all(promises)
  .then(() => console.log('Done'))
  .catch(e => console.error(e));

>All comments

That's a perfect use case for sharp.

Here's a quick demo how to do it:

const fs = require('fs')
const sharp = require('sharp')

const files = fs.readdirSync('/tmp/images')

const convert = (dir, name) => {
  const fullname = dir + '/' + name
  const i = sharp(fs.readFileSync(fullname));
  i.toFormat('webp', { quality: 80 })
  return i.toFile('/tmp/converted-images/' + name + '.webp')
    .then(() => console.log('Converted', fullname))
    .catch(e => console.log('Failed converting', fullname, e, 'skipping...'))
}

const promises = files.map(name => convert('/tmp/images/', name))

Promise.all(promises)
  .then(() => console.log('Done'))
  .catch(e => console.error(e));
Was this page helpful?
0 / 5 - 0 ratings

Related issues

OleVik picture OleVik  路  3Comments

kachurovskiy picture kachurovskiy  路  3Comments

Andresmag picture Andresmag  路  3Comments

iq-dot picture iq-dot  路  3Comments

henbenla picture henbenla  路  3Comments