[Edit]
+
0
-
0
Node.js - convert image to *.webp file (lossless compression)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43// Note: to install sharp package use: `npm install sharp` const sharp = require('sharp'); /** * Converts any image to *.webp file using lossless compression. * * @param {*} inputPath path to input image file (JPEG, PNG, WebP, AVIF, GIF, SVG, TIFF) * @param {*} outputPath path to output image file (WebP) * @param {*} callback called when file is saved or error occured */ const toWebp = (inputPath, outputPath, callback) => { const image = sharp(inputPath); image.webp({ lossless: true }); image.toFile(outputPath, callback); }; // Usage example: toWebp('input_image.png', 'output_image.webp', (error, info) => { if (error) { console.error('Error!'); } else { console.log('Saved!'); } }); // e.g. download and use: https://dirask.com/static/bucket/1631898942509-VMYrnXyYZv--image.png // See also: // // WebP (lossy compression) // 1. https://dirask.com/snippets/Node-js-convert-image-to-webp-file-lossy-compression-1RNkR1 // 2. https://dirask.com/snippets/Node-js-convert-image-to-webp-file-lossy-compression-j4v2VD // // WebP (lossless compression) // 1. https://dirask.com/snippets/Node-js-convert-image-to-webp-file-lossless-compression-pVNQVp