ZetCode

Gulp images

last modified November 15, 2026

In this article we process images with Gulp 5. We copy binary files without damaging them, optimize PNG, JPEG and SVG images with gulp-imagemin, and convert images to the WebP format with imagemin-webp.

Images in a Gulp pipeline

Images are the heaviest part of most pages, and they are often not optimized: a photo from a camera or a PNG exported from a design tool can be several times bigger than needed. Optimizing them in a build removes the manual work. The gulp-imagemin plugin runs the optimizers of the imagemin project on the files of a stream. There are plugins for JPEG (mozjpeg), PNG (optipng), SVG (svgo) and GIF; the plugin uses them by default. Other plugins, such as imagemin-webp, convert images to another format.

Both gulp-imagemin and imagemin-webp are ES modules, so the gulpfile has to be an ES module too, as in the ESM gulpfile tutorial.

Installing the project

We create a project and install Gulp, the two image plugins and gulp-rename, which changes the extension of the converted files.

$ mkdir gulp-images
$ cd gulp-images
$ npm init -y
$ npm i -D gulp gulp-imagemin imagemin-webp gulp-rename
$ mkdir -p src/img

The example project

The src/img directory has four images: a JPEG photo, two PNG images and a small SVG icon. The raster images were generated with ImageMagick; their content does not matter, but their sizes do.

src/img/icon.svg
<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">
    <!-- a red circle -->
    <circle cx="50" cy="50" r="40" fill="#ff0000"/>
</svg>

The SVG icon contains a comment and indentation that an optimizer can remove. The sizes of all the sources are as follows.

$ wc -c src/img/*
   151 src/img/icon.svg
  8172 src/img/logo.png
 96702 src/img/photo.jpg
180628 src/img/swirl.png
285653 total

The gulpfile

The gulpfile has four tasks, which we look at one by one.

gulpfile.mjs
import { src, dest } from 'gulp';
import imagemin from 'gulp-imagemin';
import webp from 'imagemin-webp';
import rename from 'gulp-rename';

export function broken() {

    return src('src/img/*')
        .pipe(dest('dist/broken'));
}

export function copy() {

    return src('src/img/*', { encoding: false })
        .pipe(dest('dist/copy'));
}

export function optimize() {

    return src('src/img/*', { encoding: false })
        .pipe(imagemin({ verbose: true }))
        .pipe(dest('dist/optimized'));
}

export function convert() {

    return src('src/img/*.{png,jpg}', { encoding: false })
        .pipe(imagemin([webp({ quality: 75 })]))
        .pipe(rename({ extname: '.webp' }))
        .pipe(dest('dist/webp'));
}

The tasks differ in the options of src and in the plugins that process the files.

Binary files and the encoding option

Gulp 5 reads files as UTF-8 text by default. That is right for scripts and stylesheets, but it damages binary files: the bytes that are not valid UTF-8 are replaced by the replacement character, so a plain copy of an image does not produce the same image. The broken task copies the images without any option; the copy task passes encoding: false to src, which turns the decoding off and keeps the content as it is.

return src('src/img/*', { encoding: false })
    .pipe(dest('dist/copy'));

We run both tasks and compare the files with the originals. The cmp command prints nothing for identical files. The SVG file is text, so it survives both ways, but the PNG and JPEG images are damaged by the first task: the file command does not even recognise the PNG as an image.

$ npx gulp broken --silent
$ npx gulp copy --silent
$ cmp src/img/swirl.png dist/broken/swirl.png
src/img/swirl.png dist/broken/swirl.png differ: byte 1, line 1
$ cmp src/img/swirl.png dist/copy/swirl.png
$ file dist/broken/swirl.png dist/copy/swirl.png
dist/broken/swirl.png: data
dist/copy/swirl.png:   PNG image data, 800 x 500, 16-bit/color RGB, non-interlaced

Optimizing images

The optimize task passes the images through imagemin() without a list of plugins, so the default optimizers are used. The verbose option makes the plugin print the savings for every file. The result is lossless for PNG and SVG; the JPEG optimizer, mozjpeg, recompresses the image with its default quality, so its result is lossy.

return src('src/img/*', { encoding: false })
    .pipe(imagemin({ verbose: true }))
    .pipe(dest('dist/optimized'));

The photo shrinks the most. The PNG with the swirl has many colors and little redundancy, so it saves only two percent, while the simple logo shrinks by a third.

$ npx gulp optimize
[13:32:38] Using gulpfile ~/Documents/prog/js/gulp-images/gulpfile.mjs
[13:32:38] Starting 'optimize'...
gulp-imagemin: ✔ icon.svg (saved 37 B - 24.5%)
gulp-imagemin: ✔ logo.png (saved 2.65 kB - 32.5%)
gulp-imagemin: ✔ photo.jpg (saved 76.4 kB - 79%)
gulp-imagemin: ✔ swirl.png (saved 3.63 kB - 2%)
gulp-imagemin: Minified 4 images (saved 82.7 kB - 29%)
[13:32:40] Finished 'optimize' after 1.29 s
$ wc -c dist/optimized/*
   114 dist/optimized/icon.svg
  5517 dist/optimized/logo.png
 20295 dist/optimized/photo.jpg
176995 dist/optimized/swirl.png
202921 total

Converting to WebP

The imagemin-webp plugin converts PNG and JPEG images to the WebP format, which is smaller than both of them. We pass the plugin to imagemin in an array; this replaces the default optimizers. The plugin changes only the content of the files, so the names still end in .png and .jpg, and rename gives them the right extension.

return src('src/img/*.{png,jpg}', { encoding: false })
    .pipe(imagemin([webp({ quality: 75 })]))
    .pipe(rename({ extname: '.webp' }))
    .pipe(dest('dist/webp'));

The quality option is a number from 0 to 100; lower values give smaller, less exact files. Three files are written, and the file command confirms that they are valid WebP images. The photo shrank from 96,702 to 12,196 bytes. The names of the sources must be unique without the extension: photo.png and photo.jpg would both become photo.webp and one would overwrite the other, as the Gulp rename tutorial shows.

$ npx gulp convert
[13:32:40] Using gulpfile ~/Documents/prog/js/gulp-images/gulpfile.mjs
[13:32:40] Starting 'convert'...
gulp-imagemin: Minified 3 images (saved 268 kB - 93.8%)
[13:32:40] Finished 'convert' after 98 ms
$ wc -c dist/webp/*
 2196 dist/webp/logo.webp
12196 dist/webp/photo.webp
 3346 dist/webp/swirl.webp
17738 total
$ file dist/webp/photo.webp
dist/webp/photo.webp: RIFF (little-endian) data, Web/P image, VP8 encoding, 800x500, Scaling: [none]x[none], YUV color, decoders should clamp

Using the images

A page can offer WebP images and fall back to the original format. The picture element lists the sources in the order of preference, and the browser takes the first that it supports.

<picture>
    <source srcset="img/photo.webp" type="image/webp">
    <img src="img/photo.jpg" alt="A photo">
</picture>

To have both versions in the output, we can run the optimization and the conversion as two tasks with parallel, which is explained in the Gulp series and parallel tutorial. A cleaned output directory, as in the Gulp clean tutorial, makes sure that no old images remain.

Source

gulp-imagemin on npm, imagemin-webp, Gulp src, Image file types on MDN

In this article we have processed images in Gulp 5: we saw why binary files need encoding: false, optimized PNG, JPEG and SVG files with gulp-imagemin, and converted images to WebP. See also the Gulp src and dest and Gulp 5 tutorials.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Gulp tutorials.