Giter Site home page Giter Site logo

color-convert's Introduction

color-convert

Color-convert is a color conversion library for JavaScript and node. It converts all ways between rgb, hsl, hsv, hwb, cmyk, ansi, ansi16, hex strings, and CSS keywords (will round to closest):

import convert from 'color-convert';

convert.rgb.hsl(140, 200, 100);             // [96, 48, 59]
convert.keyword.rgb('blue');                // [0, 0, 255]

const rgbChannels = convert.rgb.channels;     // 3
const cmykChannels = convert.cmyk.channels;   // 4
const ansiChannels = convert.ansi16.channels; // 1

Install

$ npm install color-convert

API

Simply get the property of the from and to conversion that you're looking for.

All functions have a rounded and unrounded variant. By default, return values are rounded. To get the unrounded (raw) results, simply tack on .raw to the function.

All 'from' functions have a hidden property called .channels that indicates the number of channels the function expects (not including alpha).

import convert from 'color-convert';

// Hex to LAB
convert.hex.lab('DEADBF');         // [ 76, 21, -2 ]
convert.hex.lab.raw('DEADBF');     // [ 75.56213190997677, 20.653827952644754, -2.290532499330533 ]

// RGB to CMYK
convert.rgb.cmyk(167, 255, 4);     // [ 35, 0, 98, 0 ]
convert.rgb.cmyk.raw(167, 255, 4); // [ 34.509803921568626, 0, 98.43137254901961, 0 ]

Arrays

All functions that accept multiple arguments also support passing an array.

Note that this does not apply to functions that convert from a color that only requires one value (e.g. keyword, ansi256, hex, etc.)

import convert from 'color-convert';

convert.rgb.hex(123, 45, 67);      // '7B2D43'
convert.rgb.hex([123, 45, 67]);    // '7B2D43'

Routing

Conversions that don't have an explicitly defined conversion (in conversions.js), but can be converted by means of sub-conversions (e.g. XYZ -> RGB -> CMYK), are automatically routed together. This allows just about any color model supported by color-convert to be converted to any other model, so long as a sub-conversion path exists. This is also true for conversions requiring more than one step in between (e.g. LCH -> LAB -> XYZ -> RGB -> Hex).

Keep in mind that extensive conversions may result in a loss of precision, and exist only to be complete. For a list of "direct" (single-step) conversions, see conversions.js.

Color Space Scales

Conversions rely on an agreed upon 'full-scale' value for each of the channels. Listed here are those values for the most common color spaces

rgb

channel full-scale value
r 255
g 255
b 255

hsl

channel full-scale value
h 360
s 100
l 100

hsv

channel full-scale value
h 360
s 100
v 100

hwb

channel full-scale value
h 360
w 100
b 100

cmyk

channel full-scale value
c 100
m 100
y 100
k 100

hex

channel full-scale value
hex 0xffffff

keyword

channel value
name any key from color-name

apple

channel full-scale value
0 65535
1 65535
2 65535

gray

channel full-scale value
g 100

Contribute

If there is a new model you would like to support, or want to add a direct conversion between two existing models, please send us a pull request.

License

Copyright © 2011-2016, Heather Arthur. Copyright © 2016-2021, Josh Junon.

Licensed under the MIT License.

color-convert's People

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

color-convert's Issues

UIColor

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?

Hue component of HCG color is wrong by 120° then converting from RGB or CMYK

Steps to reproduce

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 ]

Description

Then converting color to HCG from RGB or CMYK Hue component of the color appears to be offset by 120°.

Current behavior

var convert = require('color-convert')
convert.rgb.hcg.raw([250, 0, 255])
[ 178.8235294117647, 100, 0 ]

Expected behavior

var convert = require('color-convert')
convert.rgb.hcg.raw([250, 0, 255])
[ 298.8235294117647, 100, 0 ]

Cause?

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.

下载taro-ui出错,这跟node-sas是有什么关系

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.

inaccurate ansi256 conversion

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.

Create distancing algorithm to return closest keyword from input RGB.

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).

Is this library still maintained?

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?

Breaking Uglify

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.

mishoo/UglifyJS#2449

Identity transformation

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?

loss of accuracy

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.

Convertation is differrent

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!

Convert to import/export definitions

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.

backward conversion isn't accurate

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])

Incorrect conversion RGB to HSV

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:
image
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?

Add string conversions

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)'

Consistent named colour lookup for color-convert & color-string

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!

hex

It would be good to add hex conversion support.

Inaccurate xyz to lab.

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.

ansi256 => ansi16 squashes a bunch of grayscale values and basic colors to black

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.

Failure to convert XYZ to RGB and back

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?

Perform BFS at publish time

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.

Can we get a proper changelog?

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.

hsla support?

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?)

hsl conversions are off

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

hsl2hsv returns NaN

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);

Converting hex to hsv directly?

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

add useful constants / scales

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:

  • 'max'
  • 'scale'
  • 'unit'

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

Convert multiple hsv to hex failed

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)

Cannot read property '1' of null

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!

image

image

cannot find module 'color-name'

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)

Extremely slow conversion from rgb to hsv

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

Converting between hex to hsv and hsv to hex changes values

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?

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.