Skip to content

Recipe: compress to WebP

uhop edited this page Dec 1, 2014 · 5 revisions

WebP is a next generation image format spearheaded by Google, which provides advanced compression options. While grunt-tight-sprite doesn't produce it directly, it is easy to create one.

While there are many utilities to do this compressing as a post-processing step, I came to rely on cwebp. In this recipe I call it using grunt-exec plugin.

Installing dependencies

First, you should install cwebp using official instructions, if it is not readily available on your platform. Now you can move it to be in your default path, or call it directly by absolute name. The example below assumes a default path.

Gruntfile

Now we are ready to write a gruntfile:

grunt.loadNpmTasks('grunt-tight-sprite');
grunt.loadNpmTasks('grunt-exec');

grunt.initConfig({
  tight_sprite: {
    icons: {
      options: {
        hide: "tests/icons"
      },
      src: ["tests/icons/*/**/*.{png,jpg,jpeg,gif}"],
      dest: "tests/icons/sprite.png"
    }
  },
  exec: {
    compress_icons: {
        cmd: "cwebp -preset icon -m 6" +
          "-o <%= tight_sprite.icons.dest %>.webp " +
          "<%= tight_sprite.icons.dest %>"
    }
  }
});

grunt.registerTask("sprite", ["tight_sprite:icons", "exec:compress_icons"]);

As you can see, our compression command uses a reference to access a sprite file. Leveraging this grunt feature helps to keep all information in one place: later on we can modify the location of a sprite, and our compression task will "know" that automatically.

cwebp can convert JPEG and PNG files. It understands a lot of options to fine-tune a final sprite. Please consult its documentation to select options suitable for your graphic assets.

With this gruntfile we can build our sprite any time we want manually, or incorporate it in other tasks:

grunt sprite