Chris 2pha Brown

Chris Brown

Drupal, Javascript, Three.js, 3D

website blog

Gulp imagemin with the pngquant plugin

I found it hard to find an example of how to use gulp-imagemin with a plugin, specifically in my case, the imagemin-pngquant plugin.
The difference seen between using compressing a .png with the default compressor that is included in gulp-imagemin and pngquant was substantial.
I was converting a 100px x 100px 21.3KB .png. The png compressor that comes with gulp-imagemin (optipng) produced a file that was 19KB, but using pngquant produced a file that was 3.63KB. Quite a large difference.
Obviously it is worth using, but examples I found on the interwebs all seems to be wrong. After a bit of trial and error I got it working and though I would post it here for future reference.
Keep in mind, I did not set any of the options for each case.
In the future I will probably look at using gulp-image instead as it seems to also support pngquant and there is actually some decent documentation..

var imagemin = require('gulp-imagemin');
var pngquant = require('imagemin-pngquant');

var inFiles = "src/images/*.png";
var outFiles = "build/images";

// Standard imagemin
gulp.task('compressStandard', function(){
  return gulp.src(inFiles)
    .pipe(imagemin())
    .pipe(gulp.dest(outFiles))
});

// imagemin using pngquant plugin
gulp.task('compressQuant', function(){
  return gulp.src(inFiles)
    .pipe(imagemin([pngquant()]))
    .pipe(gulp.dest(outFiles))
});

// Using quant plugin and sending options
// Send the pngquant options object directly to the function
// the second argument send to the imagemin function is the imagemin options object
gulp.task('compressQuantOptions', function(){
  return gulp.src(inFiles)
    .pipe(imagemin([pngquant({quality: '50'})], {verbose: true}))
    .pipe(gulp.dest(outFiles))
});