29a.ch by Jonas Wagner

dont-crop a library to fit gradients to images

Example Photo by Abed Ismail

After a bit of a break finally something to open source again. Dont-crop is a javascript/typescript library to fit a gradient to an image and extract the primary colors (color palette, dominant colors).

It’s using simple algorithms to keep the code compact. About 1 kb is required for just fitting gradients and another kb for extracting the dominant colors.

By operating on downscaled images the code runs fast as well. Fitting a gradient to the image data takes less than 25 μs on my machine.

Uses

I initially wrote the code when hacking on a photo gallery which might or might not be released in the future. I used it to select border colors and background gradients for images.

As a bonus it also serves as an extremely compact ‘blur up image loading’ approach.

Maybe someone else can find other uses as well.

Fitting gradients

The gradient fitting is performed using simple linear-regression on each color channel.

You can think of it as fitting a straight line through a graph of the y position and color channel value.

Example

Extracting the palette

Extracting the dominant colors is performed using another simple algorithm k-means clustering.