Convert Images to webp with Node

2.6k Views Asked by At

I have a script to convert images to node, but am having an issue where I receive the successful message, yet nothing is output.

import imagemin from "imagemin";
import webp from "imagemin-webp";

var outputFolder = "./FSS-assets/webp";            // Output folder
var PNGImages = "./FSS-assets/*.png";         // PNG images
var JPEGImages = "./FSS-assets/*.jpg";        // JPEG images

imagemin([PNGImages], outputFolder, {
  plugins: [webp({
      lossless: true // Losslessly encode images
  })]
}).then(function() {
  console.log("Images converted!");
});

imagemin([JPEGImages], outputFolder, {
  plugins: [webp({
    quality: 65 // Quality setting from 0 to 100
  })]
}).then(function() {
  console.log("Images converted!");
});

I am running

  • node v14.16.0
  • imagemin v8
  • imagemin-webp v6

I have also tried using a relative folder path to no avail. This is on Windows 10.

2

There are 2 best solutions below

1
On BEST ANSWER

That's because imagemin has 2 params input and options You are giving 3params.

From the Doc:

imagemin(input, options?)

Returns Promise<object[]> in the format {data: Buffer, sourcePath: string, destinationPath: string}.

So for your code it will be:

imagemin([PNGImages], {
  destination: outputFolder,
  plugins: [webp({
      lossless: true // Losslessly encode images
  })]
}).then(function() {
  console.log("Images converted!");
});

0
On

It looks like you just need to adjust your parameter structure slightly. To be ([images], { destination: ‘/output directory’, plugins: {});

const files = await imagemin(['images/*.{jpg,png}'], {
destination: 'build/images',
plugins: [
    imageminJpegtran(),
    imageminPngquant({
        quality: [0.6, 0.8]
    })
]
});

Hope this helps & works.