Java, Web

Delivering compressed SVG format(SVGZ) using Spring Boot

SVG stands for Scalable Vector Graphics. Literally, it’s a graphic format that is scalable, jaggy free  and compact (in most cases).
Most draw tools natively support loading and saving SVG files. You’ll find the format useful when you’re annoyed with jaggy images on your corporate web site.

Today I replaced a png logo on our internal system with an SVG file.

The file size was supposed to be shrunk, but the truth is that it grew from 18.26kb to 431kb. Then I was reminded of the compressed SVG format which Illustrator is offering. And the file size got minified to 3,688 bytes.

But it doesn’t get rendered correctly.

It tuns out that Spring Boot and the Web server do not specify the Content-Encoding header to gzip OOTB.

Serving compressed SVG files

I might be able to configure that on Nginx side, but in order to get the image loaded correctly on my local environment as well, I implemented a very simple ServletFilter.

/*
Copyright 2020 Samuraism Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import org.springframework.stereotype.Component;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class SVGZFilter extends HttpFilter {
@Override
public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (request.getRequestURI().endsWith(".svgz")) {
response.setHeader("Content-Encoding","gzip");
}
chain.doFilter(request, response);
}
}

view raw
SVGZFilter
hosted with ❤ by GitHub

And now it works 🙂

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です