qix- / color-convert Goto Github PK
View Code? Open in Web Editor NEWPlain color conversion functions in JavaScript
License: MIT License
Plain color conversion functions in JavaScript
License: MIT License
This prints out all the grayscale values at the end of ansi256:
for (let i = 232; i < 256; i++) {
console.log(colorConvert.ansi256.ansi16(i));
}
Which results in:
30
30
30
30
30
30
30
30
30
30
30
30
37
37
37
37
37
37
37
97
97
97
97
97
Note that the first half of the scale all gets crushed to 30 black
, but I'd expect values from ~236-243 to be converted to 90 bright black
, just like in the second half values are converted to white and bright white.
Right now, a BFS happens at inclusion time which is needless overhead. The BFS should happen at publish time since that graph won't change at any other point.
This should be in the form of a build script with a pre-publish
hook.
Is it possible/recommended to supply color-convert with a JSON file of values?
input:
console.log(r, g, b);
console.log(convert.rgb.hsl(...convert.hsl.rgb(r,g,b)))
output:
0 51 255
[180, -51, 255]
Hi, first thanks for this great library!
I have an issue converting an XYZ value to RGB and back, it seems that for some values this works, but for others not. I could not find any range for the XYZ values in the readme (as for the other values), maybe it is related to that?.
This conversion matches (after rounding):
const startXYZ = [47.854955042890886, 29.320696241557958, 21.87902240817543]
const _rgb = convert.xyz.rgb(startXYZ);
const endXYZ = convert.rgb.xyz(_rgb) // => [ 48, 29, 22 ]
However, the following conversion is a mismatch (and quite some other value):
const startXYZ = [ 20, 87, 79 ]
const _rgb = convert.xyz.rgb(startXYZ);
const endXYZ = convert.rgb.xyz(_rgb) // => [ 48, 76, 75 ]
I have been fiddling with the color-space
library as well, but that seems to have the same result (colorjs/color-space#48). Is this a bug in the conversion algorithm?
Just try this:
conv.hsl(conv.rgb(223, 240, 216).hsl()).rgb()
It returns
[ 222, 239, 215 ]
I think it is because hsl
values are integers.
Needs to be tested, but chalk/chalk#433 (comment) outlines how you would short-circuit between the two conversions.
Hello! 👋
I noticed a minor inconsistency between color-convert & color-string; this module uses an internal lookup hash for the CSS named colours, whereas color-string uses an external module.
I think it might be nice to standardise both of these modules to use the external module, especially as color relies on both modules and therefore the browser bundle size is inflated. The hashes are pretty much identical. 😄
I can send a patch implementing this change if you're amenable.
Thanks!
The reason appears be to hsv is first converted to rgb, then to hex, the conversion fails around 3rd try.
Example
var convert = require('color-convert');
var hsv1 = { h: 4.945966547104157, s: 57.993720392282746, v: 100 };
var hsv2 = { h: 174.14398641457106, s: 43.56065729758369, v: 100 };
var hsv3 = { h: 12.711132565529491, s: 75.74526836055404, v: 100 };
var hsv4 = { h: -144.65989307844234, s: 74.91559036016699, v: 100 };
var hsv5 = { h: 99.64804531609816, s: 56.35261559103195, v: 100 };
console.log(convert.hsv.hex(hsv1.h, hsv1.s, hsv1.v));
console.log(convert.hsv.hex(hsv2.h, hsv2.s, hsv2.v));
console.log(convert.hsv.hex(hsv3.h, hsv3.s, hsv3.v));
console.log(convert.hsv.hex(hsv4.h, hsv4.s, hsv4.v));
console.log(convert.hsv.hex(hsv5.h, hsv5.s, hsv5.v));
output
FF776B
90FFF4
FF673E
/Users/me/Desktop/test/node_modules/color-convert/conversions.js:634
var integer = ((Math.round(args[0]) & 0xFF) << 16)
^
TypeError: Cannot read property '0' of undefined
at convert.rgb.hex (/Users/me/Desktop/test/node_modules/color-convert/conversions.js:634:33)
at /Users/me/Desktop/test/node_modules/color-convert/route.js:59:10
at Object.wrappedFn [as hex] (/Users/me/Desktop/test/node_modules/color-convert/index.js:39:16)
at Object.<anonymous> (/Users/me/Desktop/test/test.js:12:25)
at Module._compile (internal/modules/cjs/loader.js:654:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:665:10)
at Module.load (internal/modules/cjs/loader.js:566:32)
at tryModuleLoad (internal/modules/cjs/loader.js:506:12)
at Function.Module._load (internal/modules/cjs/loader.js:498:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:695:10)
Hi,
I started using your library to convert from an undefined source to hsv. Without thinking I ended up coding a colorConvert.hsv.hsv conversion, which obviously doesn't exist. Would it be possible/reasonable to add a a no-op or identity transformation (ie output = input) when source and destination during the route construction?
At the moment I've trapped it an dealt with it specially, but it would be really nice not to have to have different code in the transformation path :)
Thoughts?
When converting from RGB to HSV precision plays a big role. So when rounding some of the numbers, we don't convert the right color. The example is clear when converting the #f6f6f6 color to HSV. According to the internet resources we get:
To be more clear color will be - 0, 0, 96.47. As this library performs rounding on the end, it rounds it to 0, 0, 96, which is incorrect, because the RGB representation of this color will be #f5f5f5. I went through the source code, and found out, that we perform rounding on all models, but in some cases, it can cause serious difficulties because of this rounding bug. Maybe we should round to 1 decimal place instead?
Hello - thanks for your code!
I used 'color-convert' to create an array of colors sweeping through hues like so:
const elements = 16;
var colors = [...Array(elements)].map((_, index) => convert.hsv.rgb([360*(index/elements), 100, 100]))
However figuring out the values of 360
and 100
felt a tad hacky (even if 360 is a fairly well accepted range for hue - my first guess was 60
by glancing at the source code). I hail from a more embedded-oriented land and the fast HSV -> RGB conversion code that I admire provides constants to indicate what scale is used for the hue:
#define HSV_HUE_SEXTANT 256
#define HSV_HUE_STEPS (6 * HSV_HUE_SEXTANT)
#define HSV_HUE_MIN 0
#define HSV_HUE_MAX (HSV_HUE_STEPS - 1)
#define HSV_SAT_MIN 0
#define HSV_SAT_MAX 255
#define HSV_VAL_MIN 0
#define HSV_VAL_MAX 255
This keeps me from ever guessing what scale I should use.
I would definitely enjoy making a PR that adds some of these useful landmarks to the 'color-convert' landscape. They can serve not only in HSV but also RGB, HSL, and maybe more. With these kinds of additions we would enjoy re-writing my lines as:
const elements = 16;
var colors = [...Array(elements)].map((_, index) => convert.hsv.rgb([convert.hsv.h_scale*(index/elements), convert.hsv.s_scale, convert.hsv.v_scale]))
Naming of these constants could change of course if something else seems more appropriate. Maybe:
So, is this something you are interested in? If so do you have a preference for how these constants are delivered to users?
Regards,
O
Hey Qix!
I have used your rgb to hsv algorithm for a while, until I tried writing my own algorithm. I did a performance test on a high-res image (6000 x 4000 pixels). My algorithm was 12 times (!!!) faster than your algorithm. I haven't looked into your code to see what we do differently, but I took the time to give you my solution.
Context: I used your algorithm to do a pixel-by-pixel conversion from rgb to hsv, to calculate the difference in hue. So practically I'm iterating 24 000 000 times. Using your algorithm, the entire loop took about 12 seconds on chrome on an early 2015 macbook pro. My solution ended up taking a bit over 1 second to complete.
So yea here it is:
const rgb_hsv = (red, green, blue) => {
let rdif,
gdif,
bdif,
h, s;
const r = red / 255,
g = green / 255,
b = blue / 255,
v = Math.max(r, g, b),
diff = v - Math.min(r, g, b),
diffc = (c) => {
return (v - c) / 6 / diff + 1 / 2;
}
if (diff == 0) {
h = s = 0;
} else {
s = diff / v;
rdif = diffc(r);
gdif = diffc(g);
bdif = diffc(b);
if (r === v) {
h = bdif - gdif;
} else if (g === v) {
h = (1 / 3) + rdif - bdif;
} else if (b === v) {
h = (2 / 3) + gdif - rdif;
}
if (h < 0) {
h += 1;
} else if (h > 1) {
h -= 1;
}
}
return [
Math.round(h * 360),
Math.round(s * 100),
Math.round(v * 100)
];
}
Edit: context
color-name version 1.1.3 marked as EOL . Hence please update it's version in this module
convert.rgb.hex(250,0,0) = FA0000 ???
what?
Hi,
I getting different values converting from RGB to HSL and then back
var convert = require('color-convert');
console.log("A38E8E", " => ", convert.hex.hsl("A38E8E")); // Result A38E8E
console.log([0, 10, 60], " => ", convert.hsl.hex(0, 10, 60)); // Result A38F8F. Expected A38E8E
Converting A38E8E I get [0, 10, 60]
Converting [0, 10, 60] I get A38F8F. Not A38E8E!
Currently rgb
-> keyword
only works if you're giving it the exact RGB value. I feel this is rather useless unless you converted from a keyword originally. If the RGB values aren't exact, it returns undefined
.
What would be great is to map out the color points and use a 3D distancing algorithm to find the nearest keyword in RGB space.
Of course this would be a much greater overhead than a simple reverse lookup (as is being done now) but would return meaningful results.
At the very least, it'll be a fallback if an exact match isn't found (complementing the existing functionality). Alternatively, it could be its own conversion model altogether (though I don't think that makes much sense).
You can try in node REPL: 'A1C9FF' !== 'A1CAFF'
> var conf = require('color-convert')
undefined
> conv.hex.hsv('A1C9FF')
[ 214, 37, 100 ]
> conv.hsv.hex([214,37,100])
'A1CAFF'
> conv.hsv.hex([214,37,100])
If [0,0,0]
is passed into hsl2hsv
, [0,NaN,0]
is returned because of a divide by 0 error here sv = (2 * s) / (l + s);
Conversions should be able to handle strings as input and output. It looks like it would be pretty straight forward to connect it with your package color-string, at least for the supported colors.
convert.hsl.hex('hsl(256,100,17)') -> '0C002C'
convert.hsl.hex.str('hsl(256,100,17)') -> '#0C002C'
convert.hsl.hex.str([256, 100, 17]) -> '#0C002C'
convert.hsl.rgb('hsl(256,100,17)') -> [12, 0, 44]
convert.hsl.rgb.str('hsl(256,100,17)') -> 'rgb(12, 0, 44)'
Converting from cmyk only gives back Cyan, Magenta, Yellow or black and not the color that was inserted.
I am running into a breaking issue, that i am unable to find any information on when including chalk in the initial start up of Angular. Color-name does not seem to exist in the project, though it is called in the "conversions.js" file. I have run npm install with global and cannot get the issue to resolve. Any help on understanding how to resolve this is greatly appreciated.
Edit: This is being run through Visual Studio code, and on Windows 10
Error: Cannot find module 'color-name'
at Function.Module._resolveFilename (module.js:469:15)
at Function.Module._load (module.js:417:25)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object. (C:\users\jpearson\serverConnection\my-app\node_modules@angular\cli\node_modules\chalk\node_modules\ansi-styles\node_modules\color-convert\conversions.js:2:19)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
Here we are converting from RGB to HCG and then back.
Note color components are very far apart.
var convert = require('color-convert')
convert.hcg.rgb.raw(convert.rgb.hcg.raw([250, 0, 255]))
[ 0, 255, 249.99999999999991 ]
Then converting color to HCG from RGB or CMYK Hue component of the color appears to be offset by 120°.
var convert = require('color-convert')
convert.rgb.hcg.raw([250, 0, 255])
[ 178.8235294117647, 100, 0 ]
var convert = require('color-convert')
convert.rgb.hcg.raw([250, 0, 255])
[ 298.8235294117647, 100, 0 ]
https://github.com/Qix-/color-convert/blob/master/conversions.js#L668
4 is added twice.
This is most likely it, but I'm not 100% sure.
And throw when invalid.
Looking at the breaking change information in your changelog because I wanted to migrate from 1.x to 2.x, and couldn't find any.
I recommend using NPM Package stanrdard-version
and start using conventional-commits
.
I have tried to use 'Dark Red' as keyword but it doesn't recognize it. Do you have a list with accepted words?
There's no information about the license in package.json file
Title.
var cc = require("color-convert")
var hslColors = ["250, 100%, 96%", "250, 98%, 86%", "250, 96%, 78%",
"250, 12%, 46%", "30, 100%, 80%", "30, 72%, 62%", "30, 6%, 46%", "30, 72%, 62%", "250, 14%, 18%", "252, 14%, 28%", "30, 100%, 66%"];
for(var i=0; i < hslColors.length; i++){
console.log(hslColors[i] +" in hex is " + cc.hsl2hex(hslColors[i]));
console.log(hslColors[i] +" in ansi is " + cc.hsl2ansi(hslColors[i]));
console.log(hslColors[i] +" in ansi16 is " + cc.hsl2ansi16(hslColors[i]));
}
250, 100%, 96% in hex is 000000
250, 100%, 96% in ansi is 16
250, 100%, 96% in ansi16 is 30
250, 98%, 86% in hex is 000000
250, 98%, 86% in ansi is 16
250, 98%, 86% in ansi16 is 30
250, 96%, 78% in hex is 000000
250, 96%, 78% in ansi is 16
250, 96%, 78% in ansi16 is 30
250, 12%, 46% in hex is 000000
250, 12%, 46% in ansi is 16
250, 12%, 46% in ansi16 is 30
30, 100%, 80% in hex is 000000
30, 100%, 80% in ansi is NaN
30, 100%, 80% in ansi16 is 30
30, 72%, 62% in hex is 000000
30, 72%, 62% in ansi is NaN
30, 72%, 62% in ansi16 is 30
30, 6%, 46% in hex is 000000
30, 6%, 46% in ansi is NaN
30, 6%, 46% in ansi16 is 30
30, 72%, 62% in hex is 000000
30, 72%, 62% in ansi is NaN
30, 72%, 62% in ansi16 is 30
250, 14%, 18% in hex is 000000
250, 14%, 18% in ansi is 16
250, 14%, 18% in ansi16 is 30
252, 14%, 28% in hex is 050505
252, 14%, 28% in ansi is 16
252, 14%, 28% in ansi16 is 30
30, 100%, 66% in hex is 000000
30, 100%, 66% in ansi is NaN
30, 100%, 66% in ansi16 is 30
It appears that hex to hsv is not idempotent as far as I can understand
var start = 'D52121';
var hsv = convert.hex.hsv(start);
var finish = convert.hsv.hex(hsv);
assert.equal(start, finish);
// AssertionError: 'D52121' == 'D62020'
Is this expected behaviour?
The current version is 2.0.1
but the Releases page and the Changelog don't describe what breaking changes happened in 2.0.0.
PS D:\work\trao-2.1.6-ts> yarn add taro-ui
yarn add v1.17.3
[1/4] Resolving packages...
[2/4] Fetching packages...
info [email protected]: The platform "win32" is incompatible with this module.
info "[email protected]" is an optional dependency and failed compatibility check. Excluding it from installation.
info [email protected]: The platform "win32" is incompatible with this module.
info "[email protected]" is an optional dependency and failed compatibility check. Excluding it from installation.
[3/4] Linking dependencies...
warning "@tarojs/mini-runner > [email protected]" has unmet peer dependency "@babel/core@^7.0.0".
warning "@tarojs/mini-runner > [email protected]" has unmet peer dependency "stylus@>=0.52.4".
error An unexpected error occurred: "EPERM: operation not permitted, unlink 'D:\work\trao-2.1.6-ts\node_modules\node-sass\vendor\win32-x64-64\binding.node'".
info If you think this is a bug, please open a bug report with the information provided in "D:\work\trao-2.1.6-ts\yarn-error.log".
info Visit https://yarnpkg.com/en/docs/cli/add for documentation about this command.
We are planning to use this library for color conversions and it looks great, the only missing part is it doesn't provide conversion to xyY color space.
please include that.
I wanted to use this in Discord.js, but the color of embed is a rgb without ",", so I want a function with "," removed.
Thanks for this awesome library!
It seems like converting #282629
returns 59
(#5f5f5f
).
console.log(convert.hex.ansi256('#282629'));
However, I think 235
(#262626
) is a better 256-color approximation of #282629
.
I'm using 2.0.1 of color-convert
.
Lots of Swift color formats, but SwiftUIRGB seems to be the most prominent I believe. Is there a more common equivalent or could color-convert output this format as well?
Hi there,
I'm loving color-convert
. One problem that I've run into, though, is that I'm unable to directly convert hex
into hsv
and vice versa. The following two lines do work to give an accurate conversion:
var rgb = convert.hex.rgb(json.currentHEX);
var hsv = convert.rgb.hsv(rgb);
Is it the case that I have to use the aforementioned lines, or am I missing some way to get a direct conversion without use of an rgb
conversion as an in-between? I understand that it is a tiny inconvenience, however, it would be great if I could simply use:
var hsv = convert.hex.hsv(json.currentHEX);
Thank you in advance for your help,
Kind regards, Tom
The constants used in xyz to lab conversions are not accurate...
As an example, places where we use 0.008856 are actually supposed to be (6/29)^3. There are a lot more constants that are not accurate. I didn't go through all of them.
This has caused problems for me because I'm building a color-related library that's implemented in multiple languages. It converts rgb to lab color space, do some basic arithmetic and then convert back to rgb. (Yes, I used the xyz.lab.raw
version) For javascript, I used color-convert as a dependency. And this has produced inconsistent results for different implementations.
hsla is way that css can define color, so it's something this library might want to handle.
Are there plans to handle hsla? (Would the repo authors be interested in a PR for it?)
In version 5 of chalk
it is written that the function keyword
has been removed and it is suggested to use this library. On npm I can see that it is years since it is not published, so is it still maintained?
There is a different copyright information for this component in the LICENSE file
Copyright (c) 2011-2016 Heather Arthur [email protected]
and the README file.
Copyright © 2011-2016, Heather Arthur and Josh Junon.
Which one is correct?
It would be good to add hex conversion support.
Forgive me if I've asked about this already, but:
looking to figure out how to convert to this "RGB" format:
set the background color to {26214, 26214, 39321}
This will allow color-convert
to be tree-shakable, meaning only the conversions that are used are actually emitted into bundled code.
This should happen alongside #56.
Hello, I'm using chartjs in an Electron application which uses color-convert. I get the following error on launch but I haven't figured out why. Was working fine on a previous computer but has been giving me issues since moving over to a new laptop.
Potentially could be associated with node-gyp issues I have also been getting since moving over.
Any help would be appreciated, thanks!
We are planning to use this library for color conversions and it looks great, the only missing part is it doesn't provide conversion to xyY color space.
please include that.
colorConvert.hsl.hex( colorConvert.hex.hsl( '#008877' ) );
// output: 008A7A
I know this is a whiny ticket, but I'd be willing to try some sort of refactor here.
Seems like Uglify-es doesn't like minifying this file, it ends up in a runtime error. I opened the ticket here.
Thoughts on just doing the change here to fix it? I can investigate.
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.