How to Convert SVG Sprite into PNG Images

How to Convert SVG Sprite into PNG Images

If you want to use SVG sprites for your icons, you can find several great generators which can create a robust icon system for you. Unfortunately, some of these services don’t generate icons in PNG format and SVG is not supported in IE8 and some older browsers on iOS and Android. If you often change icons or their colors, it is annoying to always use a graphic editor to update PNG images.

Gulp is a streaming build system which uses Node.js and I decided to use it to automate this task. Luke Whitehouse wrote about workflow, in which separate SVG files are converted into PNG files and SVG sprite. In our workflow, we convert SVG sprite into separate files and then convert them into PNG format. Sample project is viewable on GitHub.

At the beginning we define external config file which contains options of PNG images and relative path to SVG sprite.

At first part of our gulp task we convert SVG sprite into separate files.

At the end we use gulp-svg2png to convert separate SVG files into PNG files and gulp-gm to resize our PNG files. Gm is an interface of GraphicsMagick and ImageMagick tools for image manipulation in Node.js. We have to install one of these tools (using Homebrew or Chocolatey).

Gm provides many functions for imagine manipulation which we can use in our gulp task. If we want to generate PNG sprite, gulp-svgfallback generates PNG sprite from SVG icons. Moreover, we can include image compression or generates images into different sizes.

NEED A FULL STACK WEB DEVELOPER? LET'S BUILD SOMETHING.

GET IN TOUCH
3 COMMENTS
  • Tomáš Stankovič
    Reply

    Nice solution Andrej.

  • netyou
    Reply

    Thanks a lot for this!
    I had a great big mess with a sprite that was not being maintained. I used only the svg generating code to have a look at the content of the sprite and cleared out some junk from the sprite.

    You helped me a lot.

    One thing to point out is that you’re missing the colorName variable on line 28 of the second code snippet.

    1. Andrej Gajdos
      Reply

      Thanks @netyou:disqus, I am glad this post help someone 🙂 If you want to check complete code, you can take a look here https://github.com/AndrejGajdos/svg-sprite-to-png/blob/master/gulpfile.js

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: