creating / optimizing svgs
illustrator cleanup | svg optimizer plugin

Creating / Optimizing SVGs

 

Tools to create SVGs

Tools for SVG

 

Now that we covered the basics of the SVG internals, we will take a look at some tools to work with SVG files.

Browser support

As of Internet Explorer 9, all major browsers support SVG: IE 9, Mozilla Firefox, Safari, Google Chrome and Opera. Mobile devices with Webkit-based browsers also support SVG. On older or smaller devices, chances are that SVG Tiny is supported.

Inkscape

URL: www.inkscape.org

One of the most important tools for a graphics format is a decent drawing program. Inkscape offers state-of-the-art vector drawing, and it's open source.

Moreover, it uses SVG as its native file format. To store Inkscape specific data, it extends the SVG file with elements and attributes in a custom namespace, but you can also choose to export as plain SVG.

Adobe Illustrator

URL: www.adobe.com/products/illustrator/

Before Adobe acquired Macromedia, it was the most prominent promoter of SVG. From this time stems the good support of SVG in Illustrator. However, the resulting SVG often shows some quirks, that make it necessary to post-process it for general applicability.

Apache Batik

URL: xmlgraphics.apache.org/batik/

Batik is a set of open source tools under the roof of the Apache Software Foundation. The toolkit is written in Java and offers almost complete SVG 1.1 support, as well as some features that were originally planned for SVG 1.2.

Batik offers a viewer (Squiggle), a rasterizer for PNG output, an SVG pretty printer to format SVG files, and a TrueType-to-SVG-Font converter.

Together with Apache FOP Batik can transform SVG to PDF.

Other renderers

Several projects exist that can create a raster image from an SVG source. ImageMagick is one of the most famous command-line image processing tools. The Gnome library rsvg is used by the Wikipedia to raster their SVG graphics. Usage of headless browsers such as SlimerJS and PhantomJS are also popular for this purpose, as the image produced is closer to what the SVG will look like in the browser.

Raphael JS

URL: raphaeljs.com

This is a JavaScript library, that acts as an abstraction layer between browser implementations. Notably older versions of Internet Explorer are supported by generating VML, a vector markup language, that is one of two ancestors of SVG and exists since IE 5.5.

Snap.svg

URL: snapsvg.io

A newer JavaScript abstraction layer from the same author of Raphael JS. Snap.svg is designed for modern browsers and therefore supports the newest SVG features like masking, clipping, patterns, full gradients, groups. It does not support the older browsers that Raphael does.

Google Docs

URL: www.google.com/google-d-s/drawings/

Drawings from Google Docs can be exported as SVG.

Science

The well-known plotting tools xfig and gnuplot both support exporting as SVG. To render graphs on the web JSXGraph supports VML, SVG and canvas, automatically deciding which technology to use based on browser capabilities.

In GIS (Geographic Information System) applications SVG is often used as both storage and rendering format. See carto.net for details.

More tools!

The W3C offers a list of programs that support SVG.

WINNER!! Compressor

https://imageoptim.com/mac
seems to do as well as all other tools – but with easy gui (mac only)

SVGO for CLI

https://github.com/svg/svgo

Other Ways to Use SVGO

SVGO - Optimizer

 

svgooptimizer

 

SVG Optimizer is a Node.js-based tool for optimizing SVG vector graphics files.

Why?

SVG files, especially those exported from various editors, usually contain a lot of redundant and useless information. This can include editor metadata, comments, hidden elements, default or non-optimal values and other stuff that can be safely removed or converted without affecting the SVG rendering result.

Installation

npm -g install svgo

or

yarn global add svgo

CLI usage

svgo one.svg two.svg -o one.min.svg two.min.svg

Or use the --folder/-f flag to optimize a whole folder of SVG icons

svgo -f ./path/to/folder/with/svg/files -o ./path/to/folder/with/svg/output

See help for advanced usage

svgo --help

Configuration

Some options can be configured with CLI though it may be easier to have the configuration in a separate file. SVGO automatically loads configuration from svgo.config.js or module specified with --config flag.

module.exports = {
  multipass: true, // boolean. false by default
  datauri: 'enc', // 'base64', 'enc' or 'unenc'. 'base64' by default
  js2svg: {
    indent: 2, // string with spaces or number of spaces. 4 by default
    pretty: true, // boolean, false by default
  }
}

SVGO has a plugin-based architecture, so almost every optimization is a separate plugin. There is a set of built-in plugins. See how to configure them:

module.exports = {
  plugins: [
    // enable a built-in plugin by name
    'builtinPluginName',
    // or by expanded version
    {
      name: 'builtinPluginName'
    },
    // some plugins allow/require to pass options
    {
      name: 'builtinPluginName',
      params: {
        optionName: 'optionValue'
      }
    }
  ]
}

The default list is fully overridden if the plugins field is specified. To extend the default list use the extendDefaultPlugins utility:

const { extendDefaultPlugins } = require('svgo');
module.exports = {
  plugins: extendDefaultPlugins([
    {
      name: 'builtinPluginName',
      params: {
        optionName: 'optionValue'
      }
    }
  ])
}

To disable one of the default plugins use the active field:

const { extendDefaultPlugins } = require('svgo');
module.exports = {
  plugins: extendDefaultPlugins([
    {
      name: 'builtinPluginName',
      active: false
    }
  ])
}

See the list of the default plugins:

module.exports = {
  plugins: [
    'removeDoctype',
    'removeXMLProcInst',
    'removeComments',
    'removeMetadata',
    'removeEditorsNSData',
    'cleanupAttrs',
    'inlineStyles',
    'minifyStyles',
    'cleanupIDs',
    'removeUselessDefs',
    'cleanupNumericValues',
    'convertColors',
    'removeUnknownsAndDefaults',
    'removeNonInheritableGroupAttrs',
    'removeUselessStrokeAndFill',
    'removeViewBox',
    'cleanupEnableBackground',
    'removeHiddenElems',
    'removeEmptyText',
    'convertShapeToPath',
    'convertEllipseToCircle',
    'moveElemsAttrsToGroup',
    'moveGroupAttrsToElems',
    'collapseGroups',
    'convertPathData',
    'convertTransform',
    'removeEmptyAttrs',
    'removeEmptyContainers',
    'mergePaths',
    'removeUnusedNS',
    'sortDefsChildren',
    'removeTitle',
    'removeDesc'
  ]
}

It's also possible to specify a custom plugin:

const anotherCustomPlugin = require('./another-custom-plugin.js')
module.exports = {
  plugins: [
    {
      name: 'customPluginName',
      type: 'perItem', // 'perItem', 'perItemReverse' or 'full'
      params: {
        optionName: 'optionValue',
      },
      fn: (ast, params, info) => {}
    },
    anotherCustomPlugin
  ]
}

API usage

SVGO provides a few low level utilities. extendDefaultPlugins is described above.

optimize

The core of SVGO is optimize function.

const { optimize } = require('svgo');
const result = optimize(svgString, {
  // optional but recommended field
  path: 'path-to.svg',
  // all config fields are also available here
  multipass: true
})
const optimizedSvgString = result.data

loadConfig

If you write a tool on top of SVGO you might need a way to load SVGO config.

const { loadConfig } = require('svgo');
const config = await loadConfig()

// you can also specify a relative or absolute path and customize the current working directory
const config = await loadConfig(configFile, cwd)

Built-in plugins

Plugin Description Default
cleanupAttrs cleanup attributes from newlines, trailing, and repeating spaces enabled
inlineStyles move and merge styles from <style> elements to element style attributes enabled
removeDoctype remove doctype declaration enabled
removeXMLProcInst remove XML processing instructions enabled
removeComments remove comments enabled
removeMetadata remove <metadata> enabled
removeTitle remove <title> enabled
removeDesc remove <desc> enabled
removeUselessDefs remove elements of <defs> without id enabled
removeXMLNS removes the xmlns attribute (for inline SVG) disabled
removeEditorsNSData remove editors namespaces, elements, and attributes enabled
removeEmptyAttrs remove empty attributes enabled
removeHiddenElems remove hidden elements enabled
removeEmptyText remove empty Text elements enabled
removeEmptyContainers remove empty Container elements enabled
removeViewBox remove viewBox attribute when possible enabled
cleanupEnableBackground remove or cleanup enable-background attribute when possible enabled
minifyStyles minify <style> elements content with CSSO enabled
convertStyleToAttrs convert styles into attributes enabled
convertColors convert colors (from rgb() to #rrggbb, from #rrggbb to #rgb) enabled
convertPathData convert Path data to relative or absolute (whichever is shorter), convert one segment to another, trim useless delimiters, smart rounding, and much more enabled
convertTransform collapse multiple transforms into one, convert matrices to the short aliases, and much more enabled
removeUnknownsAndDefaults remove unknown elements content and attributes, remove attributes with default values enabled
removeNonInheritableGroupAttrs remove non-inheritable group's "presentation" attributes enabled
removeUselessStrokeAndFill remove useless stroke and fill attributes enabled
removeUnusedNS remove unused namespaces declaration enabled
prefixIds prefix IDs and classes with the SVG filename or an arbitrary string disabled
cleanupIDs remove unused and minify used IDs enabled
cleanupNumericValues round numeric values to the fixed precision, remove default px units enabled
cleanupListOfValues round numeric values in attributes that take a list of numbers (like viewBox or enable-background) disabled
moveElemsAttrsToGroup move elements' attributes to their enclosing group enabled
moveGroupAttrsToElems move some group attributes to the contained elements enabled
collapseGroups collapse useless groups enabled
removeRasterImages remove raster images disabled
mergePaths merge multiple Paths into one enabled
convertShapeToPath convert some basic shapes to <path> enabled
convertEllipseToCircle convert non-eccentric <ellipse> to <circle> enabled
sortAttrs sort element attributes for epic readability disabled
sortDefsChildren sort children of <defs> in order to improve compression enabled
removeDimensions remove width/height and add viewBox if it's missing (opposite to removeViewBox, disable it first) disabled
removeAttrs remove attributes by pattern disabled
removeAttributesBySelector removes attributes of elements that match a CSS selector disabled
removeElementsByAttr remove arbitrary elements by ID or className disabled
addClassesToSVGElement add classnames to an outer <svg> element disabled
addAttributesToSVGElement adds attributes to an outer <svg> element disabled
removeOffCanvasPaths removes elements that are drawn outside of the viewbox disabled
removeStyleElement remove <style> elements disabled
removeScriptElement remove <script> elements disabled
reusePaths Find duplicated elements and replace them with links disabled

 

 


 

https://www.sitepoint.com/crash-course-optimizing-and-exporting-svgs-in-adobe-illustrator/

When you begin working with SVG, it is important to understand how to create, export, and optimize your SVG files for the browsers that will render them.

However, before we start, you need to understand one thing clearly. The optimization of an SVG file begins with its creation and continues all the way to export. Like any HTML web page, it’s difficult to fix a poorly built SVG file after it’s completed.

Sure, you can use optimization tools after export, but this automated approach can break your file in all kinds of unexpected ways. Having a solid working knowledge of good manual SVG optimization concepts will hold you in good stead from the start.

This is exactly what you will learn today.

Creating SVGs in Illustrator

When you create a graphic in Illustrator—which is intended for SVG export—you need to perform some steps and considerations required to make the final output properly optimized for web. Let’s explore them now.

Set the Correct Color Space

Illustrator — as most vector illustration software — was originally designed for print production, and therefore its color space is set to CMYK by default. RGB is much more appropriate for web and screen use, and has a wider gamut (range of colors) than CMYK. So, when you create new document, make sure the color mode is set to RGB – as you can see in the image below.

Give your drawing a proper structure

An SVG file is not like a regular bitmap image — a grid of pixels. It’s a text document that has a specific structure.

Like an HTML document, you can select and manipulate individual elements separately. To do this, you’ll need to use their names as a reference. I’ve found it’s always much easier to create these labels during visual editing in Illustrator, rather than later.

For that reason, it’s important to give a meaningful name to each graphic element as you make it. Here is what you need to know when you create a graphic in Illustrator:

  • Illustrator Layers and Layers Groups names are used as IDs for SVG groups
  • Illustrator Symbols names are used as IDs for SVG symbols
  • Illustrator Graphic Styles names are used as CSS classes

In the images below, you can see in action how names from an Illustrator file reflect to the exported SVG.

 

1498711348layersandstyles

1498711368webelements

Simplify your shapes whenever possible

The shapes in an SVG drawing are described with coordinate points. The more points a drawing has, the larger the file size and more difficult it is to edit and maintain. Creating small, efficient files makes your life easier later.

To solve this issues, you need to use the fewest possible number of points to create the shapes you need. This can be achieved in several ways.

Use Primary SVG shapes instead of SVG paths whenever possible

Using simple elements like line, rect, and circle has some significant advantages.

Firstly, simple shapes are much more readable for humans – it’s self-evident that a circle is a circle when we see it in our SVG code, but the code for a path can be anything until we see it render.

Secondly, simple shapes almost always produce smaller file sizes and less code, which make them easier for maintain and edit. You can also control them more easily with their direct attributes such as x, y, cx, cy, instead of point coordinates as it is with paths.

To see what I mean, in the image below you can see a simple circular shape defined once as a SVG circle element and once as a SVG path. Though they render identically, it’s clear that the SVG shape is smaller and more versatile. Be aware that some graphics editors – Fireworks’s SVG export extension was an example – automatically convert SVG shapes to paths when you export. Obviously, try hard to avoid this.

1498711360styling

simplify

Simplify your paths

A path is nothing more than an array of coordinate points. To simplify a path means to cut out some of its points, which will lead to less path data and smaller file size. To do so you can use Object > Path > Simplify… command or Warp Tool. In both cases, the main point is to reduce the path’s points maximally without loosing the quality of visual appearance.

In the images below, you can see how Illustrator’s simplify process reduces path points from 32 to 23 — which is about 25% — and how this reflects to the code. The path data is decreased while the visual quality still remains at a good level.

before and after

 

Decide whether to convert text to paths

In SVG graphics, text is a standalone element and as such it is searchable, accessible, and easily re-editable. This is a valuable quality for text to have. However, if you want to guarantee your text looks exactly the way you designed it everywhere, your end-user will need to have access to the correct fonts. This means choosing a common fonts — which limits your creativity — or providing a web font.

If precise text rendering is more important than editability — for example, in a logo — you can convert it into paths by using Type > Create Outlines command or by setting this option in the export panel as you’ll see later on.

Bear in mind that convert a lot of text to paths, the file size can increase drastically – so think carefully before converting.

filters1498711364texttopaths

Use ‘SVG filters’ in preference to Illustrator or Photoshop Filter Effects

Illustrator offers a set of SVG Filters that are applied live in the browser (Effect > SVG Filters). While Illustrator or Photoshop Effects are always permanently ‘baked into’ your raster images embedded inside the SVG, SVG filters can be changed or removed at any time with a few keystrokes.

You can also create re-usable filters and/or edit them via Apply SVG Filter dialog.

svgfilters1498711345filters

Fit artboard to drawing

If you want your SVG to be displayed predictably, it’s good habit to always to trim your artboard to the drawing before. The artboard dimensions are the dimensions of the exported SVG viewport, and any white space in the artboard will be generated as white space inside the viewport.

Depending on situation you can use Object > Artboards > Fit to Artwork Bounds or Object > Artboards > Fit to Selected Art command.

In the image below, the left star will be exported with the surrounding white space, while the right star will be exported with its proper dimensions.

Exporting SVG in Illustrator

Since version 2015.2, Illustrator CC has shipped with a new export panel created for web-optimized SVG files. In this section we’ll see how to use it.

Note: For those of you using older version of Illustrator here is an appropriate tutorial.

 

When your graphic is ready for production, select File > Export > Export As… command, then select SVG as option for the file type and hit Export button. You should see the following panel:

svgexprot1

Let’s explore the options presented in more detail.

Styling

There are three way to style your SVG and they are presented in the first dropdown list.

  1. The first is to use internal CSS (i.e. a <style> block), which is generally considered the best option following the Separation of Concerns principle.
  2. The second method is to use inline CSS styles (i.e. ).
  3. And the third method is to use SVG presentation attributes .

In the image below, you can see the difference between these three options.

stylingoptions

Font

If you want to convert your text to outlines, here you can instruct Illustrator to do so. If you want to preserve your text editability, then select SVG option. Outlined text gives you complete visual control of your typography, but at a significant cost – file sizes blow out and text loses editability and searchability.

Note: SVG fonts will be removed from SVG 2 and is considered as a deprecated feature with support being removed from browsers.

Images

Here you can choose how you treat any raster images in your SVG. You can choose to keep them as external files, or to embed them into the SVG as DataURIs. Often Link is a useful choice as it makes the parent SVG file dramatically smaller and, as such, far more manageable in your code editor.

However, the Embed option does have one great, overriding advantage: embedded images can never become unlinked/separated from their ‘parent SVG’. SVGs using linked resources will show the missing image icon the first time the SVG is downloaded, uploaded or moved without its ‘child images’.

Keep this in mind if you require portability in your SVG.

As a general rule, you’ll avoid many future headaches if you can simply avoid using pixel-based graphics in your SVGs whenever you can.

 

Object IDs

Generally the best option is to select Layer Names, because this will give you meaningful names for your individual SVG elements. Minimal uses random letter-numbers, and Unique uses large random combination of characters.

objectids

Decimal

This option defines how many decimal places your coordinates will have filled after the decimal point. Higher numbers means more precise paths, while lowest number produces less verbose code and small file size.

As you can see from the graphic below, the path with 5 decimal places if far larger than the same path with 1 decimal – yet visually identical.

Keep in mind that we’re talking about 100ths and 1000ths of a pixel here. Higher values will only ever be necessary only if your graphic is very small or requires incredible precision. In most cases, sticking to value of 1 decimal place – will be the best option.

decimal

Minify

Check this option only if you’re exporting a final version of your graphic for production and you are sure that the file won’t be edited anymore.

Responsive

In theory, this option removes the width and height attributes from your SVG document – making it more responsive. However, in most cases, this is not enough to make your SVG truly responsive for all browsers and especially for IE. We’ll explore a fix for this problem in a follow up tutorial.

TIP: It’s always a good idea to keep your original .ai file as your source, and then to export SVG copies with different settings from that parent file.

When you choose Export As… command, in the appearing export dialog you may have noticed an additional option called Use Artboards. It becomes useful when you use multiple artboards—for example, when you create a set of icons—and you want each artboard to be exported as a separate SVG file.

useartboards

As you’ve seen above, a lot of optimization takes place during the creation and export of your SVG. However, you may want to further optimize your file with some specialized tool, such as SVGO or its web GUI-fied version SVGOMG.

Be aware that you do need to be careful when using these tools. They can easily break your document functionality. My advice is to use manual optimization whenever it’s possible and use automated optimization tool only if it’s necessary and with caution.

Conclusion

I don’t think I’m going out on a limb to pronounce SVG as the future of web vector graphics. It’s hard to see a situation where SVG doesn’t continue to gain more power along the time. If you haven’t dived in yet, it will be good and wise investment to start learn it now.

We have SVG 2 appearing on the horizon with lots of powerful, new features to play with will. Exciting times ahead.

Scroll to Top