Image Resizing with Gulp

Writing your own tools and scripts is always a very satisfying thing. You take something that used to take a long time and then you automate it.

JavaScript task runners like gulp are a great deal of help when automating tasks with the help of a large amount of community packages for almost every purpose.

For the GegenWind Blog we frequently resizes images with a gulp task that looks a bit like this:

var gulp = require('gulp');
var gm = require('gulp-gm');
var newer = require('gulp-newer');
var imagemin = require('gulp-imagemin');

gulp.task('default', function () {
    gulp.src('source/**/*.*')
    .pipe(newer('resized'))
    .pipe(gm(function(gmfile) {
      gmfile.setFormat('jpg').quality(90);
      return gmfile.resize(1600, 1500);
    }))
    .pipe(imagemin())
    .pipe(gulp.dest('resized'));
});

The dependencies can be installed with:

npm install --save gulp gulp-gm gulp-newer gulp-imagemin

Gulp-newer makes sure that no images is resized again if the source file hasn't changed (believe me, this is good if you're resizing a lot of images and you don't want to wait forever, when changing one).

The point of the script is to take a folder / directory of images on the harddrive, convert them to jpg and to resize them.

The output of the script is not very interesting, but here we go:

[13:19:50] Using gulpfile ~/projects/gulp-image-resize/gulpfile.js
[13:19:50] Starting 'default'...
[13:19:50] Finished 'default' after 11 ms
[13:19:54] gulp-imagemin: Minified 8 images (saved 324 kB - 9.1%)

The size comparison from our full size shots is usually very significant:

% ls -1 -sh source
total 64M
2.9M IMG_0474-2.jpg
4.3M IMG_0474.jpg
4.0M IMG_0477-2.jpg
5.7M IMG_0477.jpg
 23M IMG_0481.jpg
6.2M IMG_0482-2.jpg
1.6M IMG_0482-4.jpg
 17M IMG_0482.jpg
% ls -1 -sh resized
total 3.1M
208K IMG_0474-2.jpg
284K IMG_0474.jpg
260K IMG_0477-2.jpg
356K IMG_0477.jpg
648K IMG_0481.jpg
308K IMG_0482-2.jpg
544K IMG_0482-4.jpg
548K IMG_0482.jpg

So that's how we keep the image loading on our blog snappy, even on mobile. From 64 MB to 3.1 MB for 8 images we want to look good is alright I think.

Anyways, check out the GegenWind Blog for the images ;)

Tagged with: #Gulp #gulp-gm #gulp-imageoptim #gulp-newer

Thank you for reading! If you have any comments, additions or questions, please tweet or toot them at me!