Compressing a transparent PNG like a JPEG with rokka got even easier

We took the technique of “simulating” alpha channels in JPEGs with SVG one step further and made it even easier to use with rokka. Now you just have to set the jpg.transparency.autoformat stack option to true and rokka will return the most appropriate format, if the rendered image has a visible alpha channel. No need to build the SVG on the client side anymore.

Compared to the approach described last week, we had to include the actual binary images with a data-uri attribute. Most browsers don’t load remote resources defined in a “remote” svg. This will make the SVG response quite a bit bigger than the binary formats, but gzip compression helps here enough.

Another obstacle was detection, if the client actually supports SVG. Firefox and Safari for example just send “*/*” in their accept header, when requesting an img in HTML. But consulting Can I use? revealed that browsers not supporting that are very much negligible. Therefore, rokka will now return a SVG, as long as there is “*/*” in the accept header (or image/svg+xml is explicitely mentioned), when this stack option is set. Unless the browser states that it knows how to handle WebP, then we return that (since that’s still smaller than the SVG approach). If no accept header is set (or no */* is in it), we return the whole thing as PNG.

All this only applies if you request a jpg, set the right stack option and the rendered image has a visible alpha channel. In all other cases, there’s no magic applied and just the stated format is returned (meaning for example, it’s delivered as normal jpg, if there’s no visible alpha channel).

Below we load the image at–options-jpg.transparency.autoformat-true/7ed6427d9edaaaa60bf21f503022d56a208962aa.jpg. It should render as WebP (Size: 17.8 kB) in Chrome and as SVG in all other browsers (Size: 20.5 kB). Or as PNG (Size: 24 kB), if you download it eg. with curl without any accept header.

Leave a Reply