lokesh / color-thief Goto Github PK
View Code? Open in Web Editor NEWGrab the color palette from an image using just Javascript. Works in the browser and in Node.
Home Page: https://lokeshdhakar.com/projects/color-thief/
License: MIT License
Grab the color palette from an image using just Javascript. Works in the browser and in Node.
Home Page: https://lokeshdhakar.com/projects/color-thief/
License: MIT License
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.
I'm running my first test of createPalette, and when the code gets here:
var newPalette = cmap.palette();
I'm getting an error: Object false has no method palette
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!
Okay so not really an issue, just a public service announcement from The Curator, David Higgins (@Higgo)
-- This repo has been included in The Github Pirates' Chest.
What is this about?
The Github Pirates is a constantly updated resource for those interested in HTML5, CSS3, and JavaScript.
You should find out more about this project below:
OR, Download The Chest:
it'd be righteous to have some html5 drag n drop filereader action so people can try their own images.
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!
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! :)
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);
//});
you can check it yourself, using the demo page..
add
<style>img { width: 100px; height: 100px; }</style>and see the results..
i think i know why.. i'll try to fix it
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!
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)'
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;
}
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,
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
Is there a way to build this with NPM without having to build canvas, since it calls python and visual studio
Dragging an image onto the page in Firefox only opens that file, instead of triggering the drag event. I opened Chromium and then it worked. Firefox 35.
How would you go about doing this? Something like appending multiple images to the cavas element color-thief creates?
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?
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?
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?).
I cannot find a solution to make it work with phantomjs so I'm wondering if it's even possible?
You have added bower.json but have not tagged a release so bower is currently only pulling from master
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 !
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;
}
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.
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?
Is it possible to use image URLs (like http:// .. png) in imageArray instead of using local file paths?
Thanks
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
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?
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
Would be hot to have little title tags show the colour on hover of each swatch
The README says:
createPalette(sourceImage, colorCount)
returns array[ {r: num, g: num, b: num}, {r: num, g: num, b: num}, ...]
but it actually returns [ [num, num, num], [num, num, num], ...]
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!
Color-theif is a great utility, but on a newer computer it can still take a half-second or more to run through, on a somewhat large image. Why not have a web-worker version similar to what they're doing here? http://www.sitepoint.com/using-web-workers-to-improve-image-manipulation-performance/
I'm looking for a nodejs solution.
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], ... ]
}
*/
.getPalette()
not always give quantity requested
Exemple 1:
var colorThief = new ColorThief();
console.log( colorThief.getPalette(img,2).length ); // 3
Exemple 2:
http://jsfiddle.net/5cXE7/
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.
IE 9/10 IndexSizeError exception How to fix?
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!
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
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;
};
[...]
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;
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
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.
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)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.