• Stars
    star
    122
  • Rank 282,551 (Top 6 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created almost 3 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A small, dependency free javascript library to fit a gradient to an image or extract it's primary colors.

API Documentation | Demo

Tests TypeScript

Dont-crop is a small, dependency free javascript library to fit a gradient to an image or extract it's primary colors.

It can be used to pad images instead of cropping them, for a very compact blur up and what ever else you can come up with.

Examples

fitGradient()

fitGradient Photo by Abed Ismail

getPalette()

getPalette

More Examples

View the demo page to see more examples and experiment with your own images.

Installation

npm install -S dont-crop

Usage

ES Modules

import {getPalette, fitGradient} from 'dont-crop';

const image = new Image();
// the image needs to be loaded before you can pass it to dont-crop
image.onload = () => {
  console.log(getPalette(image));
  // ['#000000', ...]
  console.log(fitGradient(image));
  // 'linear-gradient(#000000, #ffffff)`
}
image.src = 'example.jpg';

CommonJS

const getPalette = require('dont-crop').getPalette;
const fitGradient = require('dont-crop').fitGradient;
// ...

React

See examples/react/index.tsx for a simple example.

NodeJS

Usage with node depends on the image processing library being used. In general an image data object needs to be constructed and passed to getPaletteFromImageData or fitGradientToImageData.

The base functions getPalette and fitGradient will not work using NodeJS. At least not without bending over backwards.

See getImageData in examples/node-sharp/example.ts for an example using sharp.

Compatibility

The code should run in all common modern browsers and node from version 12 on. It has been tested in:

  • Chrome
  • Firefox
  • Safari
  • Edge

Performance

The code is reasonably compact and built with tree shaking in mind. So your bundles will only include the features you actually use.

When using fitGradient only and bundling your code using webpack 5 dont-crop will add about 1.2 kb (0.7 gzipped) to your bundle size. getPalette will cost you a bit more than 3.2 kb (1.7 gzipped). You can use both for about 4 kb (2 gzipped).

3925 dist/both.js
1911 dist/both.js.gz
1264 dist/fitGradient.js
710  dist/fitGradient.js.gz
3261 dist/getPalette.js
1656 dist/getPalette.js.gz

Runtime performance is also fast enough not to worry about.

# on a AMD Ryzen 9 5950X
fitGradientToImageData x 19,813 ops/sec ±0.96% (97 runs sampled)
getPaletteFromImageData(fast=false) x 156 ops/sec ±0.66% (83 runs sampled)
getPaletteFromImageData(fast=true) x 645 ops/sec ±0.17% (97 runs sampled)

The versions of the functions operating on images rather than the already downscaled image data are slower. Their performance depends on the exact browser and device in question as well but it should generally be in the ballpark of a few milliseconds for reasonably sized images.

Test Coverage

The code is well covered in tests. The examples are used as end to end tests in both node and a browser (chrome via puppeteer).

Algorithms

Glad you asked. fitGradient() is using simple linear regression.

getPalete() is based on k-means. The initial clusters are chosen using a histogram. Similar clusters in the result are merged in a post processing step. This is necessary because k-means tends to return equally sized clusters whereas getPalette is supposed to return distinct clusters. The merging is tuned to preserve different hues and colors rather than returning the most prominent shades of color (which might all share a similar hue). The processing happens in the CIE Lab color space using CIE76 ΔE*.

Alternatives

Just blur the image

using a blurred version of the image as background is a very simple alternative. I think it looks a bit more busy but it requires less plumbing (just a bit of css) and will generally be faster.

If the gradient fitting is performed on the backend and cached or server side rendered this reverses and it becomes a very efficient approximation of the image.

colorthief

Provides similar functionality to getPalette. It weighs in at about 6.4k (version 2.3.2). It's been widely used since 2019 so it is definitely more battle proofen. From a quick looks it seems to be using median-cut which will likely yield a bit better results than the simplistic k-means used here.

fast-average-color

Returns a single average or dominant color color.

smartcrop.js

Smartcrop.js is another project of mine. As the name suggests it tries to find smarter crops.

Roadmap

There are plenty of interesting ways to improve this library further.

  • Grouping of colors (saturated, muted, light, dark, warm, cold)
  • Tuning of the variables involved in palette extraction potentially allowing some degree of tweaking by the user of the library
  • Weighting the linear-regression and k-means to focus on the center or edges
  • Using a more robust regression variation like Theil-Senn
  • Gamma corrected linear gradients by manually interpolating the stops

License

MIT

More Repositories

1

smartcrop.js

Content aware image cropping
JavaScript
12,766
star
2

simplex-noise.js

A fast simplex noise implementation in Javascript / Typescript.
TypeScript
1,461
star
3

smartcrop-cli

Command line interface for the smartcrop library to provide content aware image cropping.
JavaScript
316
star
4

analog-film-emulator

A web based analog film emulator/photo editor.
JavaScript
236
star
5

normalmap.js

normalmap.js is a library for creating simple interactive lighting effects using normal maps.
JavaScript
176
star
6

fluidwebgl

WebGL Fluid Simulation
JavaScript
170
star
7

Neonflames

Neon flames is a crazy online HTML5 drawing tool.
JavaScript
142
star
8

smartcrop-sharp

Node module for using smartcrop via sharp/libvips
JavaScript
109
star
9

playitslowly

Play it slowly is a software to play back audio files at a different speed or pitch.
Python
98
star
10

box2d2-js

Automatic port of box2dAS 2.0 to javascript
ActionScript
87
star
11

voxelworlds

WebGL Voxel World Generation Demo
JavaScript
73
star
12

terrain

WebGL Terrain, ocean, fog
JavaScript
71
star
13

webglice

A webgl demo, showing of an iceberg featuring hdr rendering water reflections etc.
JavaScript
36
star
14

httpripper

HTTP Ripper is a tool to rip content out of the web.
Python
34
star
15

simplex-noise-demo-synthwave

Just a little demo for simplex-noise.js 4.0
TypeScript
27
star
16

smartcrop-gm

Node module for using smartcrop via image magick
JavaScript
27
star
17

space-break

Space Break is a html5 acrade 'ball and paddle' game implemented in coffee script
CoffeeScript
23
star
18

kinect-experiments

kinect usb rocket launcher controll
Python
18
star
19

Frontendconf-2011

Source code from a live coding talk on canvas particle systems I gave at frontendconf
JavaScript
13
star
20

jquery.textCloud

jQuery plugin to create text clouds
JavaScript
12
star
21

addresscloud

Visualization of 3.7 million swiss addresses using WebGL
JavaScript
12
star
22

fluidcanvas

Fluid simulation experiment using HTML5 Canvas
JavaScript
12
star
23

guitarTrainer

A web based guitar practice tool
JavaScript
10
star
24

lanshark

P2P Filesharing Tool
Python
8
star
25

musicviz-code

Coded during my talk @takeoffconf
JavaScript
6
star
26

littlemetronome

a little metronome written using python, gtk and gstreamer
Python
5
star
27

wildwebgl

Raymarching distance fields with wild results
JavaScript
5
star
28

webrtc-pong

A simple WebRTC multiplayer game example
JavaScript
4
star
29

kalman-ts

A simplistic library for implementing kalman filters using javascript/typescript.
TypeScript
4
star
30

box2dlite

Box2Dlite changed to run on linux
C++
3
star
31

jack-pipe

Pipes a wav file through jack into another wav file.
C
2
star
32

schwermetall

3D Printed Guitar Pedal Enclosure
2
star
33

bluenoise-rs

A bit of fun generating blue noise using void and cluster
Rust
2
star
34

swirly-lens-hoods

A 3D printable lens hood that creates swirly bokeh.
1
star
35

parcel-namer-29a

probably not of interest to anyone
TypeScript
1
star