Color.kt is a modern color science library for Kotlin Multiplatform and Java.

Related tags

Colors colorkt
Overview

Color.kt

Color.kt is a modern color science library for Kotlin Multiplatform and Java. It includes modern perceptually-uniform color spaces and color appearance models, such as Oklab and ZCAM.

API documentation

Features

  • Perceptually-uniform color spaces, each with LCh (lightness, chroma, hue) representations
  • Color appearance models
  • Hue-preserving gamut mapping
    • Preserve lightness, reduce chroma (default)
    • Project towards neutral 50% gray
    • Adaptive lightness and chroma preservation
  • CIE 1931 XYZ interchange color space
    • Relative luminance
    • Absolute luminance in nits (cd/m²) for HDR color spaces
  • Automatic conversion graph
  • Gamma-correct sRGB encoding and decoding
  • Support for custom color spaces
  • Idiomatic Java API

Usage

Latest version on Maven Central

Add this library as a dependency and replace VERSION with the latest version above:

repositories {
    mavenCentral()
}

dependencies {
    implementation 'dev.kdrag0n:colorkt:VERSION'
}

If you're using the Kotlin Gradle DSL:

repositories {
    mavenCentral()
}

dependencies {
    implementation("dev.kdrag0n:colorkt:VERSION")
}

Examples

Increase colorfulness with CIELAB

Convert a hex sRGB color code to CIELAB, increase the chroma (colorfulness), and convert it back to sRGB as a hex color code:

() val lch = cielab.convert() val boosted1 = lch.copy(C = lch.C * 2).convert().toHex() ">
val cielab = Srgb("#9b392f").convert<CieLab>()
val lch = cielab.convert<CieLch>()
val boosted1 = lch.copy(C = lch.C * 2).convert<Srgb>().toHex()

Do the same thing in Oklab:

() val lch = oklab.convert() val boosted2 = lch.copy(C = lch.C * 2).convert().toHex() ">
val oklab = Srgb("#9b392f").convert<Oklab>()
val lch = oklab.convert<Oklch>()
val boosted2 = lch.copy(C = lch.C * 2).convert<Srgb>().toHex()

Advanced color appearance model usage

Model a color using ZCAM:

// Brightness of the display
val luminance = 200.0 // nits (cd/m²)

// Conditions under which the color will be viewed
val cond = Zcam.ViewingConditions(
    surroundFactor = Zcam.ViewingConditions.SURROUND_AVERAGE,
    adaptingLuminance = 0.4 * luminance,
    // Mid-gray background at 50% luminance
    backgroundLuminance = CieLab(50.0, 0.0, 0.0).toXyz().y * luminance,
    // D65 is the only supported white point
    referenceWhite = Illuminants.D65.toAbs(luminance),
)

// Color to convert
val src = Srgb("#533b69")
// Use ZCAM to get perceptual color appearance attributes
val zcam = src.toLinear().toXyz().toAbs(luminance).toZcam(cond)

Increase the chroma (colorfulness):

val colorful = zcam.copy(chroma = zcam.chroma * 2)

Convert the color back to sRGB, while preserving hue and avoiding ugly results caused by hard clipping:

val srgb = colorful.clipToLinearSrgb()

Finally, print the new hex color code:

println(srgb.toHex())

Automatic conversion

Color.kt makes it easy to convert between any two color spaces by automatically finding the shortest path in the color conversion graph. This simplifies long conversions, which can occur frequently when working with different color spaces. For example, converting from CIELCh to Oklab LCh is usually done like this:

val oklab = cielch.toCieLab().toXyz().toLinearSrgb().toOklab().toOklch()

With automatic conversion:

val oklab = cielch.convert<Oklch>()

However, keep in mind that there is a performance cost associated with automatic conversion because it requires searching the graph. Conversion paths are cached after the first use, but it is still less efficient than manual conversion; prefer manual, explicit conversions in performance-critical code.

Custom color spaces

Color.kt includes several color spaces that should cover most use cases, but you can also add your own if necessary. Simply create a class that implements the Color interface, and implement some conversions to make the color space useful:

data class GrayColor(val brightness: Double) : Color {
    fun toLinearSrgb() = LinearSrgb(brightness, brightness, brightness)

    companion object {
        // sRGB luminosity function from https://en.wikipedia.org/wiki/Relative_luminance
        fun LinearSrgb.toGray() = GrayColor(0.2126 * r + 0.7251 * g + 0.0722 * b)
    }
}

Optionally, add your new color space to the automatic conversion graph for convenient usage:

ConversionGraph.add<LinearSrgb, GrayColor> { it.toGray() }
ConversionGraph.add<GrayColor, LinearSrgb> { it.toLinearSrgb() }

If you implement a new color space this way, please consider contributing it with a pull request so that everyone can benefit from it!

You might also like...
Jetpack Compose Color Picker
Jetpack Compose Color Picker

Bundle of Stylish customizable Color pickers, selectors, colorful sliders written with Jetpack Compose enables users to choose from HSL, HSV or RGB color modes to pick Solid colors or gradients.

Hex string encoder/decoder for Kotlin/Multiplatform

Hex string encoder/decoder for Kotlin/Multiplatform. Supports Android, iOS, JavaScript and plain JVM environments.

🎨 A tiny (Kotlin) library for generating attractive colors
🎨 A tiny (Kotlin) library for generating attractive colors

🎨 A tiny (Kotlin) library for generating attractive colors

Little image processing library
Little image processing library

Poliwhirl Description This is a small image processing library done to find good color for icon background. It uses CIEDE2000 to determine what colors

A list of most useful resources for designing android apps such as all material colors and dimens, 180 Gradient background + html, social, flat, fluent, metro colors.

Timer UI Login UI Fitness UI Material-Resources-Library A list of most useful resources for designing android apps such as all material colors and dim

Color.kt is a modern color science library for Kotlin Multiplatform and Java.

Color.kt is a modern color science library for Kotlin Multiplatform and Java. It includes modern perceptually-uniform color spaces and color

A modern color science library for Kotlin Multiplatform and Java

Color.kt Color.kt is a modern color science library for Kotlin Multiplatform and Java. It includes modern perceptually-uniform color spaces and color

🎨 A color picker for Android. Pick a color using color wheel and slider (HSV & alpha).
🎨 A color picker for Android. Pick a color using color wheel and slider (HSV & alpha).

ColorPicker English | 中文 A ColorPicker for Android. Pick a color using color wheel and slider (HSV & alpha). Gradle dependencies { implementation

An app that is a one-stop destination for all the CS enthusiasts, providing resources like Information scrapping techniques, best YT channels, courses available free-of-cost, etc.  & knowledge about every domain and field that exists on the Internet related to Computer Science along with News, Jobs, and Internships opportunities in these domains along with valuable tips and hacks from mentors for a particular domain.
An app that is a one-stop destination for all the CS enthusiasts, providing resources like Information scrapping techniques, best YT channels, courses available free-of-cost, etc. & knowledge about every domain and field that exists on the Internet related to Computer Science along with News, Jobs, and Internships opportunities in these domains along with valuable tips and hacks from mentors for a particular domain.

An app that is a one-stop destination for all the CS enthusiasts, providing resources like Information scrapping techniques, best YT channels, courses available free-of-cost, etc. & knowledge about every domain and field that exists on the Internet related to Computer Science along with News, Jobs, and Internships opportunities in these domains along with valuable tips and hacks from mentors for a particular domain.

The backend of HumLib - The Human Library in Computer Science

humlib-be Backend for HumLib - The Human Library in Computer Science Development workflow We use GitHub flow as git branching strategy. It is based on

KotlinForDS - An exploration of data science using Kotlin

Kotlin Jupyter Notebook An example notebook can be found here: https://mybinder.

Collection of various algorithms in mathematics, computer science etc implemented in Kotlin for educational purposes.

The Kotlin Algorithms Implementation of different algorithms and data structures using Kotlin lang Overview The repository is a collection of open-sou

An app for Android that uses quizzes to help you learn more about computer science.

Quiz App An app for Android that uses quizzes to help you learn more about computer science. 📸 Screenshots No screenshot available yet 💻 Tech Stack

A modern JSON library for Kotlin and Java.

Moshi Moshi is a modern JSON library for Android and Java. It makes it easy to parse JSON into Java objects: String json = ...; Moshi moshi = new Mos

A color picker and a color preference for use in Android applications.
A color picker and a color preference for use in Android applications.

HSV-Alpha Color Picker for Android This library implements a color picker and a color preference for use in Android applications. Features I couldn't

This is an android studio plugin that allows you to creates new color in hex format based on a percentage (0-100) and a base color you specify.

alpha-color Description This is an android studio plugin that allows you to creates new color in hex format based on a percentage (0-100) and a base c

For color lovers! A simple but powerful Android color picker
For color lovers! A simple but powerful Android color picker

#DEPRECATED Credits for the logo goes to Hafiz Ahmmed (https://github.com/hafizahmmed) ColorBox library Features Dynamic color preview; Change the col

Color-Book - A simple color book made with compose
Color-Book - A simple color book made with compose

Color-Book A simple color book made with compose

Comments
  • Color conversion precision error

    Color conversion precision error

    I was playing around with the library - great work by the way - and encountered some issues when converting back to sRGB.

    I noticed them when creating an awt.Color after a few conversions using the library and noticed the sRGB float value was out of range. You can easily reproduce the issue with the following code:

        val srgbColor = Srgb(testColor)
        val oklabColor = srgbColor.convert<Oklab>()
        val computedSrgbColor = oklabColor.convert<Srgb>()
        val awtColor = java.awt.Color(computedSrgbColor.r.toFloat(), computedSrgbColor.g.toFloat(), computedSrgbColor.b.toFloat())
    

    The value of computedSrgbColor has a value of r which is 1.0000000001775198, when converted back to Float it rounds back to 1.0. However both the value of g and b, even when converter to float fall out of the range [0,1], and are in fact negative (respectively -6.415840168402798E-8 and -3.9362722935143425E-7).

    I was wondering if they are both just expected rounding errors which are safe to be coerced in the range [0,1], or I am missing something which isn't obvious.

    For clarification I'm just using the conversion to awt.Color to easily preview them in the debugger :)

    opened by FilippoVigani 0
  • Add Okhsl

    Add Okhsl

    Hi, this looks like a very promising library!

    It would be great to add Okhsl, the cylindrical representation of Oklab:

    https://bottosson.github.io/posts/colorpicker/ https://bottosson.github.io/posts/colorpicker/#source-code

    This would specifically add support for perceptual saturation adjustments, which would boost use cases like palette generation.

    opened by aaronadamsCA 2
  • ZCAM results are slightly different from the paper

    ZCAM results are slightly different from the paper

    The results of our ZCAM implementation are slightly different from the official ZCAM examples in the supplementary document. For example, the paper provides the following values for Example 1 (chromatically adapted to D65 using Luxpy's implementation of CAT02, because we don't support chromatic adaptation yet):

    hz = 196.3524
    Qz = 321.3464
    Jz = 92.2520
    Mz = 10.5252
    Cz = 3.0216
    Sz = 19.1314
    Vz = 34.7022
    Kz = 25.2994
    Wz = 91.6837
    

    Our results:

    hz = 196.33770439109085
    Qz = 321.3462189522057
    Jz = 92.25198613424337
    Mz = 10.519364954372517
    Cz = 3.0198964626876563
    Sz = 19.12610852817541
    Vz = 34.70166837393559
    Kz = 25.88274309285123
    Wz = 91.68426229915165
    

    I've reached out to the authors for clarification, but I haven't gotten an answer for the discrepancies and it appears that they're not willing to provide source code for the reference implementation.

    This is probably related to D65 adaptation because the example inputs are not relative to D65. As such, it's unlikely to affect our primary use case where all colors come from sRGB and thus do not need adaptation, but it's still worth investigating.

    Adapted XYZ values for Example 1 (colorio, ASTM D65, CAT02, average surround, La = 264): 182.25997236, 206.57412429, 231.18612283

    bug 
    opened by kdrag0n 2
Releases(v1.0.5)
  • v1.0.5(Feb 22, 2022)

  • v1.0.4(Dec 26, 2021)

  • v1.0.3(Sep 3, 2021)

    • Reverted to ASTM D65 white point (with accurate XYZ matrices) to better match most color spaces and color appearance models
    • Improved documentation of internal ZCAM details
    • Removed redundant step in automatic graph conversion
    • Validated ZCAM implementation against all official examples to the maximum extent currently possible
    Source code(tar.gz)
    Source code(zip)
  • v1.0.2(Aug 31, 2021)

  • v1.0.1(Aug 30, 2021)

  • v1.0.0(Aug 30, 2021)

Owner
Danny Lin
Android app, custom kernel, and chatbot developer.
Danny Lin
A modern color science library for Kotlin Multiplatform and Java

Color.kt Color.kt is a modern color science library for Kotlin Multiplatform and Java. It includes modern perceptually-uniform color spaces and color

Weeb Project (WIP) 0 Oct 21, 2021
🎨 A color picker for Android. Pick a color using color wheel and slider (HSV & alpha).

ColorPicker English | 中文 A ColorPicker for Android. Pick a color using color wheel and slider (HSV & alpha). Gradle dependencies { implementation

Hong Duan 313 Dec 14, 2022
For color lovers! A simple but powerful Android color picker

#DEPRECATED Credits for the logo goes to Hafiz Ahmmed (https://github.com/hafizahmmed) ColorBox library Features Dynamic color preview; Change the col

Enrico D'Ortenzio 53 Apr 8, 2021
Color picker library for Android

andColorPicker — Color Picker library for Android ?? Handy, ?? flexible, and ⚡ lightning-fast Android color picker views and utilities. ?? Features Cl

side.codes 216 Jan 7, 2023
Color Picker — beautiful library for Android

Color Picker — beautiful library for Android Features Simple dialog builder ARGB, RGB & HSV color models Dark theme support Sliders with gradient back

Dmitriy 35 Dec 20, 2022
Utility library that extends Jetpack Compose Colors with Material Design2 colors, Color swatches like in Flutter

????♾ Utility library that expands Compose Colors with Material Design2 colors, color swatches, Material Design 3 Tonal Palettes, color names, and utility functions to convert between HSL, HSV, RGB, HCT models and to HEX or from HEX

Smart Tool Factory 18 Dec 13, 2022
Beautiful color picker dialog for Android 9+

Color-O-Matic Beautiful Color Picker dialog for Android 9+ based on VintageChroma by Pavel Sikun. Screenshots at the end of the file. Repository Add t

null 43 Jun 5, 2022
App-level wallpaper color palette generation for Android 5.0+

MonetCompat is an app-level implementation of kdrag0n's custom Monet implementation, based on his android12-extensions module. With MonetCompat you can generate color palettes from a user's wallpaper and use them anywhere in your app. It supports Android 5.0 and above (in Palette compatibility mode) and Android 8.1 and above in normal mode.

Kieron Quinn 145 Dec 18, 2022
Match a wallpaper to your color scheme

ImageTheming Change the color palette of an image to match your theme. Getting Started Use java -jar path/to/ImageTheming.jar -h to get all available

null 230 Dec 25, 2022
A component that provides an HSV color picker, written in Jetpack compose🎨

A component that provides an HSV color picker, written in Jetpack compose??

GoDaddy 270 Dec 30, 2022