GithubHelp home page GithubHelp logo

rgbaster.js's Introduction

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

rgbaster.js's People

Contributors

a-hariti avatar alfredjkwack avatar aoushana avatar briangonzalez avatar buffcode avatar eesdil avatar eltonmesquita avatar koenpunt avatar passy avatar ramiel avatar wickynilliams avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rgbaster.js's Issues

V2: Scaling at 0 or >1?

Hi,

There's no check to keep scaling within some bounds. The source code is actually commented to state that we accept a value from 0 to 1.

A couple of things come to mind:

  • Should we even allow for a value of 0? Seems to me that this is asking for trouble since the browser would allocate less than a pixel to the image.
  • Should we allow a value larger than 1? There's no logical gain here unless there's some daft punk out there who wants to test how a browser performs up-scaling in some weird way.
  • There should be a test case for all of this.

If we agree to provide lower and upper bounds then we should also gracefully handle this. How do we want to go about that? Provide no return array and just an error, or a default array and an error?

Thoughts?

Blocksize, length and transparent pixels

Not sure if I should open 3 issues or just aggregate them in one:

  • why do you use the blocksize iteration? doesnt that mean you jump over 4/5 of all pixels?
  • why do you use img.width * img.height as the length? every pixels consists of 4 values (r,g,b,a) so data.length is ~4 times bigger - always. so you should always use it
  • why not throw out transparent pixels? if data[i+3] === 0, they shouldnt account to anything, currently they make every image with transparency have black as the main color

gitignoreing package-lock.json

I think package-lock.json should not be tracked for the sake of cleaner diffs, especially that the library doesn't have any dependencies.

Option to get hexa instead of RGB ?

Hi,

I wanted to use RGBaster with Trianglify but RGBaster gives color in RGB and Trianglify get colors in hexadecimal.
What do you think about an option to get colors in their hexadecimal form ?
Thanks

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?

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

Browser support?

Hey,

I can't find any indication of which browsers are supported. It would be good to have it listed in the README or something

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.

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?

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!

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!

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.

Module support

It would be nice if you add CommonJS and AMD support rather than implicitly adding window global namespace.

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:

  • Complete re-write in Typescript
  • Improve build process
  • Setup TSLint using standard
  • Clean up APIs and rename internals that were poorly named by my past self (darn that guy)
  • Setup CI in Buildkite Semaphore
  • Create robust test suite in Jest
  • Port #30 over to the new rewrite.
  • Audit modules which are no longer used or pose a security risk
  • Autopublish module
  • 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.

The same picture on ios and android Gets the RGB different

Demo below:

var bookImg = "http://cdn11.bookln.cn/10138_B657D15628884CAAE67BC1DB1A0699B8.jpg"
RGBaster.colors(bookImg, {
  paletteSize: 30,
  exclude: ['rgb(255,255,255)'],
  success: function (payload) {
    var rgb = payload.secondary
  }
});

Transparency etc

Sorry viewing the transparency issues etc for PNG issues and couldnt quite figure out the answer from them. Is it possible or ?

node js version.

Am I supposed to write gupfile or webpack config or something?
Please add Setup in the README.

npm install rgbaster did nothing.

Can you publish 2.1.2 with the add `types` in package.json?

From vscode, on import analyze from "rgbaster";

Could not find a declaration file for module
. /home/mike/Code/portal/wallet/node_modules/rgbaster/dist/rgbaster.js implicitly has any
type.

$ npm ls rgbaster
....
└── [email protected]

There's no types entry in node_modules/rgbaster/package.json

$ grep types node_modules/rgbaster/package.json
    "@types/jest": "^23.3.9",

I sent a PR to add it, but it looks like you already have - you just need to bump the version and publish it.

Dominant color does not appear in array

Running the following image https://imgur.com/nVqeA6i with exclude [ 'rgb(0,0,0)', 'rgba(255,255,255)' ] and a palette size of 20 as options will return rgb(255,255,255) while the array of results (below) has quite a different idea in mind.

["rgb(99,137,0)", "rgb(103,140,0)", "rgb(103,140,0)", "rgb(104,141,1)", "rgb(99,137,0)", "rgb(116,146,0)", "rgb(116,146,0)", "rgb(100,138,1)", "rgb(123,149,0)", "rgb(107,141,2)", "rgb(116,146,0)", "rgb(106,140,1)", "rgb(107,141,2)", "rgb(116,146,0)", "rgb(106,140,1)", "rgb(116,146,0)", "rgb(117,157,0)", "rgb(123,149,0)", "rgb(106,140,1)", "rgb(123,148,2)"]

I'm sure I'm missing something here. Is this a bug?

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.

Many deprecated dangerous modules still in use

warning rgbaster > grunt > [email protected]: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
warning rgbaster > grunt > glob > [email protected]: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
warning rgbaster > grunt > glob > [email protected]: please upgrade to graceful-fs 4 for compatibility with current and future versions of Node.js
warning rgbaster > gulp-uglify > [email protected]: gulp-util is deprecated - replace it, following the guidelines at https://medium.com/gulpjs/gulp-util-ca3b1f9f9ac5
warning rgbaster > gulp > [email protected]: gulp-util is deprecated - replace it, following the guidelines at https://medium.com/gulpjs/gulp-util-ca3b1f9f9ac5
warning rgbaster > gulp > vinyl-fs > [email protected]: please upgrade to graceful-fs 4 for compatibility with current and future versions of Node.js
warning rgbaster > grunt > [email protected]: CoffeeScript on NPM has moved to "coffeescript" (no hyphen)
warning rgbaster > grunt > findup-sync > glob > [email protected]: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
warning rgbaster > gulp > vinyl-fs > glob-stream > [email protected]: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
warning rgbaster > gulp > vinyl-fs > glob-stream > glob > [email protected]: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
warning rgbaster > gulp > vinyl-fs > graceful-fs > [email protected]: This module relies on Node.js's internals and will break at some point. Do not use it, and update to [email protected].
warning rgbaster > gulp > vinyl-fs > glob-watcher > gaze > globule > [email protected]: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue

Looks like development of this package is stopped for a long time. Is there any plans for future development and updates?

CORS error when using a local file

I have the following functionality in an app:

I can drag an image from my local file system to the browser, using the file API I generate a data url (something like data:image/jpeg;base64:id) and use this as the src of an img.

Now I want to use this library to get the dominant color from this image and use that color as the background, but I keep getting the following error:

Cross-origin image load denied by Cross-Origin Resource Sharing policy.

Is there any way to fix this?

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.

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!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.