LCH.cr
Implementation mostly copied from chroma.js
A shard to convert LCH colors to RGB and RGB colors to LCH.
Installation
-
Add the dependency to your
shard.yml
:dependencies: lch: github: homonoidian/lch.cr
-
Run
shards install
Usage
require "lch"
LCH.rgb2lch(r: 123, g: 40, b: 123) # {32.17, 55.27, 327.61}
LCH.lch2rgb(l: 32.17, c: 55.27, h: 327.61) # {123, 40, 123}
# or LCH.rgb2lch([123, 40, 123])
# or LCH.lch2rgb([32.17, 55.27, 327.61])
# or any other Indexable
Several other, related conversion methods are public, but rgb2lch
and
lch2rgb
are the main ones.
Rough benchmark
fast path 353.81M ( 2.83ns) (± 4.35%) 0.0B/op fastest
rgb to lch 5.69M (175.74ns) (± 0.90%) 0.0B/op 62.18× slower
lch to rgb, in sRGB 9.63M (103.83ns) (± 1.00%) 0.0B/op 36.74× slower
lch to rgb with fitting into sRGB 486.06k ( 2.06µs) (± 0.59%) 0.0B/op 727.92× slower
Your numbers may be different, but in general, fitting into sRGB will always be slower because doing this requires multiple conversions and a loop.
Useful links
- An LCH color picker
- Another LCH color picker
- LCH colors in CSS: what, why, and how?
- LCH is the best color space!
P.S
I've just copied a lot of math I don't quite understand. If you do, however, feel free to make corrections & contribute!
It'd be cool to have a nice little mathematically sound LCH library for Crystal, because in practice, it makes dynamic color-choosing fun, and I believe that's exactly how programming graphics should feel!
Also, feel free to add and PR any methods/objects/things you think are related to LCH.
Contributing
- Fork it (https://github.com/homonoidian/lch.cr/fork)
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create a new Pull Request
Contributors
- Alexey Yurchenko - creator and maintainer