🎨 A simple library for extracting dominant colors from images.

Related tags

Sliders rgbaster.js
Overview

artboard

A dead simple, zero-dependency, promise-based javascript library for extracting the dominant color(s) from an image (in the browser).

npm version

👉 Version 2 was written from the ground up with a clean and modern API, a robust test suite, and is fully written in Typescript.

Installation

npm install --save rgbaster

Usage

This library exports a default function which returns a promise resolving to a sorted array with the most dominant color at index 0, secondary at index 1, so on and so forth.

[
  { color: 'rgb(0,0,255)', count: 86  },
  { color: 'rgb(9,18,42)', count: 32  },
  { color: 'rgb(120,8,202)', count: 3  },
]
import analyze from 'rgbaster'

const result = await analyze('/2px-blue-and-1px-red-image.png') // also supports base64 encoded image strings

console.log(`The dominant color is ${result[0].color} with ${result[0].count} occurrence(s)`)
// => The  dominant color is rgb(0,0,255) with 2 occurrence(s)

console.log(`The secondary color is ${result[1].color} with ${result[1].count} occurrence(s)`)
// => The  secondary color is rgb(255,0,0) with 1 occurrence(s)

Configuration options

You may pass an optional second parameter, an object, with the following options:

ignore

An array of colors to ignore (in the form of rgb) when counting colors.

const result = await analyze('/image.png', { ignore: [ 'rgb(255,255,255)', 'rgb(0,0,0)' ] })

scale

In order to achieve greater speed, you can have rgbaster scale down the image we use internally prior to analysis, thus decreasing accuracy.

const result = await analyze('/image.png', { scale: 0.6 })

Browser support

rgbaster depends on the following browser functionality:

Maintainers

About

rgbaster was created to modularize adaptive backgrounds. Check it out.

License

MIT

Comments
  • Performance [suggestion]

    Performance [suggestion]

    Hello! Recently I've used RGBaster in a project and had some performance issues. In my case, the images processed were a bit big and I couldn't resize them because that would brake the layout.

    As I dug deep debugging the page trying to find ways to optimize the script I've changed the image data loop to iterate skipping from 4 to 128 pixels and obviously, got a considerable increase in the performance. No more long frames and in my case no impact on the results.

    My suggestion is to provide a way to decrease precision so we can gain on performance when needed. It might help a lot in some cases and be of great help for other developers.

    If needed, I can provide some measurements and some examples for testing purpose.

    enhancement 
    opened by eltonmesquita 8
  • Png Image acquisition color has a problem.

    Png Image acquisition color has a problem.

    I have a png image, and when I use the RGBaster to get the color of this picture, I get only black, whether it's dominant, secondary or palette. I do not know where the problem is. I put my png image into an attached file. noimg

    opened by Bad-Show 7
  • Fix issue #12 - Colours are now unique

    Fix issue #12 - Colours are now unique

    Implements a fix to ensure colours are unique. In addition it implements ideas proposed by @buffcode in the #12 discussion such that at the end of the process we sort the variable colorCounts and return the 1.. items (thus dropping the dominant colour).

    The implementation of the new helper functions and return values also make it easy for others should they wish to amend the palette’s behaviour.

    helper functions:

    • mapPalette: changed to handle the colorCounts transformation to the desired array of objects which is then sorted in descending order.
    • fitPalette: fits the colors to the desired outcome size (eg. 10) by either cutting the palette down or filling the remainder with a default value.
    • frmtPobj: formats the object the way we like it with 2 properties.
    opened by AlfredJKwack 5
  • Could you Elaborate in Readme?

    Could you Elaborate in Readme?

    I am attempting to use this based on your instructions and first have arrived at an error message regarding an improper header. Perhaps I am missing something obvious so I just wanted to encourage anyone to elaborate in the readme i.e. mention any requirements and more of a step-by-step instruction if possible for someone newer to node in general and unfamiliar with typescript.

    I have installed the package and am attempting to run function in a script within an html file.

    opened by AKluger 4
  • import node module in js file

    import node module in js file

    Hi, thanks for your awesome module!

    I've installed the node module with npm install rgbaster and now want to import the node module in one of my js files. But there is not just a single function I can reference.

    Here is my Code:

    import rgbaster from './rgbaster';
    
    RGBaster.colors(img, {
      success: function(payload) {
        // You now have the payload.
        console.log(payload.dominant);
        console.log(payload.secondary);
        console.log(payload.palette);
      }
    });
    

    Thanks for the help!

    opened by iam-robin 4
  • switch build system from rollup to microbundle

    switch build system from rollup to microbundle

    microbundle uses rollup under the hood with support for typscript and flow, it is designed for small libraries like this and configured for different build targets. This would allow for a simplified build process, fewer dev dependencies and configurations, and multiple build targets (umd, cjs, mjs) with better minification (using terser). This PR also cleans the src directory from unecessary files.

    opened by a-hariti 3
  • Optimize

    Optimize

    this branch contains a few performance wise edits:

    1. the loop inside getCounts would continue early for transparent colors and undefined data without the need to create the rgba array for that iteration.
    2. the rgba array is created ~~with the getRgbComponents function~~ inline (with length of 3), to avoid the costly Array.from() that creates an unnecessarily big array on each iteration.
    3. reusing existing objects for colors in the countMap instead of creating new ones for every pixel ( 84c1bda725ff56dcc337c172e55a19b090cc5500)
    opened by a-hariti 3
  • npm

    npm

    Hello, I tried to install via npm npm install git://github.com/briangonzalez/rgbaster.js, but it trips up on the symlink'd package.json and says it cannot be found and errors out. Any chance of separating the package.json from bower.json (or possibly reversing the symlink?) to make this possible?

    And also would be neat to have it up on npm registry as well.

    Thank you!

    opened by coreyworrell 3
  • v2: Missing test for promise.reject(error)

    v2: Missing test for promise.reject(error)

    Hi,

    We need a test case for the promise being rejected.

    The basic structure should follow something like the below. I'm also curious why the errorHandler source code returns a simple string and not an error object. What's the thinking on that?

    const promise = new Promise((resolve, reject) => {
        reject(new Error("Something awful happened"));
    });
    promise.then((res) => {
        // This is never called
    });
    promise.catch((err) => {
        console.log('I get called:', err.message); // I get called: 'Something awful happened'
    });
    

    As always, looking for some insight here before I supply a pull request.

    opened by AlfredJKwack 2
  • v2: Missing test for Ignore color

    v2: Missing test for Ignore color

    Hi,

    There is a missing test for ignoring a color. Going by the already existing tests I would suggest something like the below:

    it('ignores a given color for images with a source', async () => {
      const img = 'http://localhost:9080/dominant-red-secondary-green.png'
      const ignoreColors = [ 'rgb(255,0,0)']
      const result = await analyze(img, { ignore: ignoreColors })
    
      expect(result[0].count).toEqual(25)
      expect(result[0].color).toEqual(green)
    })
    

    Thoughts?

    good first issue 
    opened by AlfredJKwack 2
  • Path to v2

    Path to v2

    👋Hey everyone!

    First off, I am excited to let everyone know that version 2 of rgbaster is on the way. Super huge thanks to all of those who have PR'd and helped maintain, especially @AlfredJKwack.

    Here's my plan of attack:

    • [x] Complete re-write in Typescript
    • [x] Improve build process
    • [x] Setup TSLint using standard
    • [x] Clean up APIs and rename internals that were poorly named by my past self (darn that guy)
    • [x] Setup CI in ~~Buildkite~~ Semaphore
    • [x] Create robust test suite in Jest
    • [x] Port #30 over to the new rewrite.
    • [x] Audit modules which are no longer used or pose a security risk
    • [ ] Autopublish module
    • [x] Close currently open issues and say thanks/sorry

    My goal is to make a more robust repo that is "easier" to come back to after time away.

    Stay tuned.

    opened by briangonzalez 2
  • Ignoring all rgb above rgb(180,180,180)

    Ignoring all rgb above rgb(180,180,180)

    Hello, I'm wondering if there is an easy solution to my problem.

    I'd like to ignore all rgb colors above rgb(180,180,180).

    If this would be possible in any way, would this still be doable performance-wise?

    opened by YorbenV 2
  • TypeError: rgbaster_1.default is not a function

    TypeError: rgbaster_1.default is not a function

    Hi everyone,

    We just updated our projecto to TypeScript ^4.0.3 and we getting the following error: image

    Can anyone help us reach a solution ?

    Thanks guys.

    opened by lmarcelocc 0
  • CORS test inverted in v2

    CORS test inverted in v2

    Hi,

    Functionally, what is the difference between the following two?

    TS code from v2

      if (src.startsWith('data')) img.crossOrigin = 'Anonymous'
    

    and

    JS code from v1

        if ( imgSrc.substring(0,5) !== 'data:' )
          imgObj.crossOrigin = "Anonymous";
    

    Unless I'm mistaken - which to be honest is quite possible after a long day's work - Version 2 of RGBaster has inverted the test for CORS handling of data url's.

    opened by AlfredJKwack 1
  • formatting code with prettier.

    formatting code with prettier.

    I think formatting code using prettier.js would be a good addition to the build system, with less choices (opinionated formater), ensuring everyone's contribution looks the same (upon commit using commit hooks). what do you think @briangonzalez @AlfredJKwack ?

    opened by a-hariti 1
  • Blocking UI thread when use analyze function

    Blocking UI thread when use analyze function

    I am trying to use analyze function at version 2 to get dominant color of an image, but the call blocks my UI and make a long-time no response in browser. My code is below and runtime is Angular 7.

    import analyze from 'rgbaster';
    
    // lifecycle callback
    async ngAfterViewInit() {
        const result = await analyze('../../assets/images/1542072554094.jpg');
        console.log(result);
     }
    

    I am also trying to install rgbaster.js and import analyze from 'rgbaster.js', but it don't works. I learned that the version 2 of rgbaster was written in typescript, so i think there is no any problem to using this library in Angular framework. But I hava no idea about that the analyze function doesn't work and block ui Thread and raise a crash to browser.

    Thanks for your any replies!

    enhancement 
    opened by yxunknown 9
Releases(v2.0)
  • v2.0(Dec 2, 2018)

    This is a major overhaul of the library including:

    • a complete re-write in Typescript
    • an Improved build process
    • it now leverages TSLint using standard
    • it boasts a cleaned up APIs
    • it supports CI in Semaphore
    • and includes a robust test suite in Jest

    Enjoy!

    Source code(tar.gz)
    Source code(zip)
    rgbaster.min.js(2.73 KB)
Owner
Brian Gonzalez
Web craftsman and constant tinkerer. Ideas win.
Brian Gonzalez
JavaScript library for one-directional scrolling with item based navigation support.

Sly JavaScript library for one-directional scrolling with item based navigation support. Sly supports navigation with: mouse wheel scrolling scrollbar

null 2.9k Dec 23, 2022
A lightweight carousel library with fluid motion and great swipe precision

Embla Carousel Embla Carousel is a bare bones carousel library with great fluid motion and awesome swipe precision. It's library agnostic, dependency

David 2.8k Jan 4, 2023
🦎 A jQuery plugin for extracting the dominant color from images and applying the color to their parent.

jquery.adaptive-backgrounds.js A simple jQuery plugin to extract the dominant color of an image and apply it to the background of its parent element.

Brian Gonzalez 6.6k Dec 21, 2022
This JavaScript library produces complementary gradients generated from the top 2 dominant colours in supplied images.

Grade Demo Check it out Install Download this repo and grab the grade.js file from the /docs/dist folder. Or install from npm: npm install grade-js Us

Ben Howdle 3.7k Jan 2, 2023
colors.js - get colors in your node.js console

colors.js Please check out the roadmap for upcoming features and releases. Please open Issues to provide feedback, and check the develop branch for th

cronlabspl 4 Feb 9, 2022
chakra-radix-colors provides radix-ui color palettes, automatic dark mode, and acessible colors to chakra-ui applications

chakra-radix-colors chakra-radix-colors provides radix-ui color palettes, automatic dark mode, and acessible colors to chakra-ui applications. About C

null 11 Dec 30, 2022
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
Extracting archives made easy

decompress Extracting archives made easy See decompress-cli for the command-line version. Install $ npm install decompress Usage const decompress = r

Kevin MÃ¥rtensson 367 Jan 1, 2023
A web scraping / data mining script for extracting beginner-friendly github repos from Y Combinator's company database

A web scraping / data mining script for extracting beginner-friendly github repos from Y Combinator's company database

Oscar Mier 27 Nov 24, 2022
Simple jQuery plugin that will allow users to zoom in your images, perfect for product images and galleries.

Image Zoom (jQuery) Plugin Simple jQuery plugin that will allow users to zoom in your images, perfect for product images and galleries that is less th

Mario Duarte 8 Aug 3, 2022
A simple Discord bot that will listen for HEX, RGB(a), and HSL(a) colors in a message, and provide a small image of that color.

Pigment For the teams of designers and developers out there - Pigment will listen for messages containing a HEX, RGB(a), or HSL(a) color, and provide

Conrad Crawford 17 Dec 8, 2022
JavaScript Library for creating random pleasing colors and color schemes

#PleaseJS www.checkman.io/please Please.js is a polite companion that wants to help you make your projects beautiful. It uses HSV color space to creat

Jordan Checkman 2.3k Dec 22, 2022
A tiny utility library to generate mesh gradient based on 4 RGB colors, built with vanilla js.

MeshGradient.js mesh-gradient.js is tiny utility library to generate mesh gradient based on 4 RGB colors, built with vanilla js. Installation! npm ins

Anup Aglawe 7 Jan 4, 2023
jQuery plugin for 'responsive cropping'. Dynamically crop images to fill available space without cutting out the image's subject. Great for full-screen images.

jQuery plugin for 'responsive cropping'. Dynamically crop images to fill available space without cutting out the image's subject. Great for full-screen images.

Jono Menz 3.2k Dec 30, 2022
Compare James Webb Space Telescope images to older images.

How much more powerful is the James Webb Space Telescope when compared to Hubble? Find out! More info Want to help out? CONTRIBUTING.md Blog post with

John Christensen 399 Jan 3, 2023
Easiest 1-click way to install and use Stable Diffusion on your own computer. Provides a browser UI for generating images from text prompts and images. Just enter your text prompt, and see the generated image.

Stable Diffusion UI Easiest way to install and use Stable Diffusion on your own computer. No dependencies or technical knowledge required. 1-click ins

null 3.5k Dec 30, 2022