Skip to content

Recipe: compress to JPEG XR

Eugene Lazutkin edited this page Mar 18, 2014 · 8 revisions

JPEG XR is a next generation image format spearheaded by Microsoft, 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 ImageMagick, which knows this format as JXR. In this recipe I call it using grunt-exec plugin.

Installing dependencies

First, you should install ImageMagick using official instructions, if it is not readily available on your platform. We need convert utility. 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: "convert <%= tight_sprite.icons.dest %> " +
          "-quality 75 -format JXR <%= tight_sprite.icons.dest %>.jxr"
    }
  }
});

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.

convert can process 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