Can SVG Save You from Your Fat PNGs?

Nightmares: When Internet Explorer couldn’t handle PNGs properly.

If you’ve been around long enough (i.e. early 2000's), you’ll remember a time when all we longed for was decent PNG-32 support.

While PNG-32 had much better transparency support than garden-variety GIF, Internet Explorer rendered the transparent parts as a dirty dishwater gray (see figure). It was heart-breaking.

Understandably, people gnashed their teeth and spent their nights devising ludicrous IE hacks using JavaScript and obscure Microsoft filters.

Yes, we had much better things to complain about in those days, my friends!

So when the time came that we could finally rely on PNG-32 support, we were all so happy that we’ve barely looked at PNG closely since.

PNG -32 — the bit that sucks…

As nice as PNG-32 transparency is, there has always been a price to pay for it. Large PNGs are big files — usually 4 to 5 times the equivalent JPEG.

This JPEG weighs in at just over 30kb
The same image as a PNG ticks over 135kb

But if we needed high-quality alpha transparency, we had to suck it up, right?

There’s also no flexibility with PNG-32. Where JPEG lets you select the most effective compression, PNG takes a ‘like it or lump it’ approach.

So, where does SVG come into it?

SVG has two abilities that help us out here.

  1. Because SVG is a document format (like HTML), we can embed other file formats (such as JPEGs) inside our SVG. This is explained here if you’re interested, but you don’t need to understand this.
  2. SVG also supports filters that allow you create an alpha channel (transparency mask) — not unlike those in Photoshop. For the image above we would need a mask something like this one.

So, if we were to combine these two SVG ‘super powers’, we could theoretically create a new super-efficient image file format with luscious 32-bit transparency.

But is it worth the effort?

Meet ZorroSVG

Luckily for us, Mario Klingemann (@Quasimondo) built ZorroSVG to take most of the hard work out it for us.

Simply drag your chunky transparent PNG-32s straight into ZorroSVG, choose the JPEG quality/compression setting, and you’ll receive a shiny new transparent SVG that should work in almost any modern browser.

It’s crazy easy.

As a test-drive, I took the original 878kb PNG-32 image above and threw it at ZorroSVG with the quality set at 80%.

The new SVG weights in 183kB — that’s 21% of the original size.

Here’s a CodePen showing that SVG in action.

Click to see it working on the CodePen Demo

It’s a cool concept and it might provide a nice jumping-off point for some other ideas. More on that next week.

Originally published in the SitePoint Design Newsletter.