Internet is wild and a lot of services out there can be used to accomplish image optimization on-fly.
One of my favorites is images.weserv.nl because:
Here is the code snippet I often reuse of my projects:
const imageUrl = (url, opts) =>
`https://images.weserv.nl/?${new URLSearchParams({
/* The image URL to optimize */
url,
/* In case something goes wrong, just show the image */
default: url,
/*
Compress it as much as possible (PNG).
See: https://images.weserv.nl/docs/format.html#compression-level
*/
l: 9,
/*
Reduce PNG file size.
See: https://images.weserv.nl/docs/format.html#adaptive-filter
*/
af: '',
/*
Enable image optimization for GIF and JPEG.
See: https://images.weserv.nl/docs/format.html#interlace-progressive
*/
il: '',
/*
Enable image optimization for WebP and GIF.
See: https://images.weserv.nl/docs/format.html#number-of-pages
*/
n: -1,
/*
Pass any other option.
See https://images.weserv.nl/docs/quick-reference.html
It's recommended to pass `w` for cutting down the image size.
*/
...opts
}).toString()}`
This snippet has been used for years in projects like unavatar.io, microlink.io, teslahunt.io, and counting.
Written by Kiko Beats
Kiko Beats
Web is the Platform. Programmer, Computer Science & Software Engineer.