Git Product home page Git Product logo

color-thief's People

Contributors

aaron-hanson avatar ajmeese7 avatar ali-bugdayci avatar chellem avatar dkushner avatar ibobo avatar joscha avatar kkirsche avatar kraftner avatar lokesh avatar mhahmadi avatar michaelhart avatar nbwsc avatar nobodypb avatar nspady avatar nteike avatar wangcheng 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  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

color-thief's Issues

Update 'main' attribute in bower.json

The 'main' attribute in the bower.json file currently points to a file that does not exist.

Should be dist/color-thief.min.js or src/color-thief.js

Quality less than 1 causes infinite loop.

In the comments it is written that "0 is the highest quality settings". Quality settings below 1 will always cause infinite loops:

 for (var i = 0, offset, r, g, b, a; i < pixelCount; i = i + quality) {

I propose to change the validation:

if (typeof quality === 'undefined' || quality < 1) {
        quality = 10;
    }

Lightest color from the color palette

Since i would like to use this scrip to get a color for a background (that i want to be light), I would like to know if there is a way to get from the color palette the lightest color?

Thank you!

Cleanup on error

Hi,

the current version of ColorThief does not remove the canvas if an error has been thrown.
The current versions of firefox throw an error if the passed in image has not been fully initializied (drawImage),
therefore the clean up (removeCanvas) logic is never executed,
a simply try ... finally takes care of this.

I rewrote/extended the logic this way:
added try..finally
extracted drawImage into separate function, otherwise the constructor fails and cleanup logic is never executed because image is still null.

[...]
var CanvasImage = function (image) {
this.canvas = document.createElement('canvas');
this.context = this.canvas.getContext('2d');
this.image = image;

document.body.appendChild(this.canvas);

this.width  = this.canvas.width  = image.width;
this.height = this.canvas.height = image.height;

};

CanvasImage.prototype.draw = function () {
this.context.drawImage(this.image, 0, 0, this.width, this.height);
};
[...]
ColorThief.prototype.getPalette = function(sourceImage, colorCount, quality) {

if (typeof colorCount === 'undefined') {
    colorCount = 10;
}
if (typeof quality === 'undefined') {
    quality = 10;
}

var image = null;
var palette = null;
try {
    // Create custom CanvasImage object
    image          = new CanvasImage(sourceImage);
    image.draw();

    var imageData  = image.getImageData();
    var pixels     = imageData.data;
    var pixelCount = image.getPixelCount();

    // Store the RGB values in an array format suitable for quantize function
    var pixelArray = [];
    for (var i = 0, offset, r, g, b, a; i < pixelCount; i = i + quality) {
        offset = i * 4;
        r = pixels[offset + 0];
        g = pixels[offset + 1];
        b = pixels[offset + 2];
        a = pixels[offset + 3];
        // If pixel is mostly opaque and not white
        if (a >= 125) {
            if (!(r > 250 && g > 250 && b > 250)) {
                pixelArray.push([r, g, b]);
            }
        }
    }

    // Send array to quantize function which clusters values
    // using median cut algorithm
    var cmap    = MMCQ.quantize(pixelArray, colorCount);
    palette     = cmap.palette();

} finally {
    // Clean up
    if (image != null) {
        image.removeCanvas();
    }
}
return palette;

};
[...]

Trying to get it work

I want to get color palette when i click a image. i don't know how to make it work, what should be the value of : sourceImage

image src? all image tag?

The documentation is too minimalist

Nothing work

Cross Domain Images

When I try to use an image hosted outside my server:

Unable to get image data from canvas because the canvas has been tainted by cross-origin data. color-thief.js:50
SecurityError: An attempt was made to break through the security policy of the user agent.

Is it possible to use Cross Domain images?

Thank you very much.

Building [email protected]

Is there a way to build this with NPM without having to build canvas, since it calls python and visual studio

Get dominant color from specific area

Hi, is it possible to only get the dominant color from a specific area in an image?

var canvas = document.getElementById('da-canvas');
var context = canvas.getContext('2d');
var img = new Image();
var colorThief = new ColorThief();
var bg;

img.src = 'images/thefame.jpg';
img.onload = function() {
  canvas.height = 10;
  canvas.width = this.width;
  context.drawImage(img, 0, 0, this.width, this.height);
  bg = colorThief.getColor(canvas);
  canvas.height = this.height;
  context.drawImage(img, 0, 0, this.width, this.height);
  document.getElementById('container').style.background = 'rgb(' + bg.join(',') + ')';
}

I'm trying to get only 10px from the top of the image. I thought just setting the height of the canvas will work hahaha. But it didn't.

I think this might increase the speed as well?

for colorCount < 2 or colorCount > 256

MMCQ.quantize(...) returns false for those values leading to calling palette() on false in the next statement which throws an error. perhaps the validation can change to the following:

if (typeof colorCount === 'undefined' || colorCount < 2 || colorCount > 256) {
    colorCount = 10;
}

Error demo.js line 119 to 121

Hi,
When i've uploaded 3 images to the drag and drop the pallet looks like this:
http://webtest.net.br/cthief-error.png

I fixed just removing the line from 119 to 121.
// Must wait for image to load in DOM, not just load from FileReader
//$image.on('load', function() {
showColorsForImage($image, $imageSection);
//});

Error: this.context.drawImage(imgEl, 0, 0, this.width, this.height);

EDIT Issue because I was passing the element wrong.

My doubt now is that the Chrome console gives me this error while Firebug on Firefox does not return any error in this sense.

Firefox returns this:

dominantColor = getDominantColor(thumbImage);
console.log ("Dominant color RGB: ", dominantColor);

"Dominant color RGB: [222,233,228]"

While Chrome sometimes write the log but always return the error.

Do you know why it could be happening this?

Thanks!

Error thrown when sampled image is white

I've just set up Color Thief for a project I'm working on, and during my testing it threw an error when the uploaded image was a white logo on a transparent background. I tested again with a completely white image, and the same problem occurred.

Looking at the code, this section checks if the colour value is greater than rgb(250, 250, 250). I tried taking that if statement out and it adversely affected performance. Is there a better way to handle this? Perhaps a more graceful method of failure?

MMCQ.quantize(...) can return false or undefined thus breaking the application.

cmap can become false or undefined after the following statement causing cmap.palette() in the next line to throw an error.

var cmap = MMCQ.quantize(pixelArray, colorCount);

it can be prevented with the following check and perhaps the return value can be null in such situation:

var cmap = MMCQ.quantize(pixelArray, colorCount);
var palette = cmap? cmap.palette() : null;

Color palette drastically different between two sizes of the same image

Hi,
Let's say I have two html pages, index.html and detail.html.
On the first one, a set of images are shown with their color palette;
On the second one, a particular image is shown slightly bigger.
As a result, the two color palettes are very different.

How would I get a constant palette for a same image?

Using semver tags

Hi :)

Unlike stated in issue #15 tags are not following semver (2.0 instead of 2.0.0). It prevents using tools like rails-assets that depend on semver tags.

Would it be possible to use complete version number git tags?

Thanks! :)

Register Bower package

It would be great if this used semver tags and was registered with Bower

That way you could specify something like this: "color-thief": "~2.0.0" in your bower.json and have bower install it and manage dependencies.

Areas sampling

Hello :-)

Great tool! I wondered how complex it would be to split the results for different areas.
For example, I'd like to sample only 1/3 in height of an image. to sample the sky colours.

Something like this API:

var colors = new ColorThief({
  areas: {
    sky: [0, 100%, 33%, 100%],
    ground: [33%, 100%, 66%, 100%]
  }
});

console.log(colours.getPalette(img, 8);
/*
returns {
  sky: [ [num, num, num], [num, num, num], ... ],
  ground: [ [num, num, num], [num, num, num], ... ]
}
*/

Error on Gif Images?

I get the following error in my console window when working with Gif images. Any reason why?

Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(HTMLImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap)'

drag n drop on demo page

it'd be righteous to have some html5 drag n drop filereader action so people can try their own images.

Using URLs in imageArray

Is it possible to use image URLs (like http:// .. png) in imageArray instead of using local file paths?

Thanks

Hex or rgb on hover

Would be hot to have little title tags show the colour on hover of each swatch

Canvas is appended to body, leaves image if an error occurs.

I noticed the script appends canvas to document.body element... Why?

document.body.appendChild(this.canvas)

If there's an error such as Uncaught SecurityError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D' it leaves the image at bottom of the page.

How do I display the data ?

So my code is :

<img src="img/photo.jpg" id="picture" alt="" />

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="js/color-thief.js"></script>
<script src="js/quantize.js"></script>
<script type="">
  $(document).ready(function(){
      myImage = $('#picture');
      dominantColor = getDominantColor(myImage);
      paletteArray = createPalette(myImage, 10);
  });
</script>

Ok. Now, how can I use this to display the color hex and show the palettes ? I'm sorry if my question sounds stupid....

Thanks for any help !

Simple example please

I would love to put this plugin to use on a project right now but I can't figure it out. I know a call for better documentation has been made in other requests but I would like to just ask for a simple example from someone who has made this work. I just want to extract the dominant rgb values from an image and use that to alter the background color of another element. I only need to use the first image on a page so I can target it like so: $('body > .target-image')

I am a javascript novice and my attempts to decipher the demo.js have failed. Please and thank you for any help!

p.s. And thank you for making this Lokesh! I have searched quite a bit and can find nothing else out there that does this (at least not using jQuery anyway). Help me figure it out so I can use it please!

Standardize color response format

getDominantColor returns {r: num, g: num, b: num} while createPalette returns [ [num, num, num] ... [num, num, num] ]

createPalette should return an array of items in the same format as returned by getDominantColor

Getting colors for part of an image

Hi I was wondering if it was possible to specify maybe coordinates and pixels or % of an image to get the colors from?

So if i had a square image for example is it possible to get the colors for 4 equal sections (top left, top right, bottom left, bottom right)?

I know I could crop the image and save sections but I was hoping to not have to do this.

Thanks,

Add requirejs support

Hey, guys.
It will be really nice if we add RequireJS support.
I can make Pull Request if you need this (but it seems no maintainers who can accept Pull Request, yep?).

Whites, and question on algorithm used

I noticed that whites are often not treated very well by this algorithm. Perhaps its just a more noticeable error or perhaps its an algorithmic one.

Are you using a particular academic algorithm here or are you using a home grown one? Not sure if the whites are a bug of your code or just a bug in the best algorithm we have in the business.

[enhancement] Add missing bower.json.

Hey, maintainer(s) of lokesh/color-thief!

We at VersionEye are working hard to keep up the quality of the bower's registry.

We just finished our initial analysis of the quality of the Bower.io registry:

7530 - registered packages, 224 of them doesnt exists anymore;

We analysed 7306 existing packages and 1070 of them don't have bower.json on the master branch ( that's where a Bower client pulls a data ).

Sadly, your library lokesh/color-thief is one of them.

Can you spare 15 minutes to help us to make Bower better?

Just add a new file bower.json and change attributes.

{
  "name": "lokesh/color-thief",
  "version": "1.0.0",
  "main": "path/to/main.css",
  "description": "please add it",
  "license": "Eclipse",
  "ignore": [
    ".jshintrc",
    "**/*.txt"
  ],
  "dependencies": {
    "<dependency_name>": "<semantic_version>",
    "<dependency_name>": "<Local_folder>",
    "<dependency_name>": "<package>"
  },
  "devDependencies": {
    "<test-framework-name>": "<version>"
  }
}

Read more about bower.json on the official spefication and nodejs semver library has great examples of proper versioning.

NB! Please validate your bower.json with jsonlint before commiting your updates.

Thank you!

Timo,
twitter: @versioneye
email: [email protected]
VersionEye - no more legacy software!

Bower.json has incorrect "main" property breaking automated builds

Your bower.json file has an incorrect path in the "main" property. This breaks automated script injection via Grunt and Gulp. Currently it's set to:

"main": "js/color-thief.js",

It should be:

    "main": "src/color-thief.js"

Otherwise, this is an awesome utility,
Thanks!

Percentage of color

Hello,

Is it possible to know the percentage of picked color? If on output we receive 9 colors so what is the percentage of each of them?

Thanks

Incorrect color

when i try to get color of simple one color image, it returns a little bit different RGB array. original color rgb(0:159:60) #009F3C, colorThief color rgb(4:156:60) #049C3C
a little difference, but would be good to have correct result

Exclude color in pallet output?

Is it possible to exclude a specific color (or a color range) in the pallet output? I would appreciate any help I could get on this (contact me if you can help freelance this request)

I have a collection of images with a border/frame around them then it would be helpful to specify the color of the border in order to ignore it and just focus on the actual images color pallet (without having to edit the originals, or just ignore a color for aesthetic reasons)

Error with entirely white image.

I've used your color-thief successfully apart from uploading an entirely white image. just a simple 100x100.jpg that is completely #ffffff

I couldn't get it working in my script - it has the error

Uncaught TypeError: Cannot read property '0' of null (which refers to the following line marked ****)

ColorThief.prototype.getColor = function(sourceImage, quality) {
var palette = this.getPalette(sourceImage, 5, quality);
var dominantColor = palette[0];****
return dominantColor;
};

I tried to figure it out, but then decided to try it in your live demo at http://lokeshdhakar.com/projects/color-thief/

and it breaks that too.

where are your docs?

your readme is inconclusive.

var colorThief = new ColorThief()
colorThief.getColor(sourceImage)

What is a sourceImage. Is it a URL, an Element, a File object?

I've tried to use this prior to a file upload to determine the color...
Note: the following does not work.

$('input[type="file"]').on('change', function (e) {
  var colorThief = new ColorThief()
  var color = colorThief.getColor(e.target.files[0])
})

Do you have any suggestions?

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.