ColorKit makes it easy to find the dominant colors of an image

Overview

ColorKit

ColorKit is your companion to work with colors on iOS.

Build MIT License Swift 5.1


Features

Dominant Colors

ColorKit makes it easy to find the dominant colors of an image. It returns a color palette of the most common colors on the image.

let dominantColors = try image.dominantColors()

By default, ColorKit uses an iterative process to determine the dominant colors of an image. But it also supports doing so via a k-mean clustering algorithm. Choose whichever is more appropriate for your use case.


Color Palette

ColorKit lets you generate color palettes from a collection of colors. It will automatically ensure that the best colors are picked based on a few configurable parameters like contrast ratio.
This feature is particularly powerful when combined with the dominant color calculation.

let colors = try image.dominantColors()
let palette = ColorPalette(orderedColors: colors, ignoreContrastRatio: true)

The following examples use the palette to dynamically match the color of the text and background to the album covers.


Average Color

To compute the average color of an image, simply call the averageColor function on a UIImage instance.

let averageColor = try image.averageColor()

Color Difference (DeltaE)

Perceptual color difference / comparaison is a common problem of color science.
It simply consists of calculating how different two colors look from each other, to the human eye. This is commonly referenced as the DeltaE.

ColorKit makes it a breaze to compare two colors.

let colorDifference = UIColor.green.difference(from: .white) // 120.34

While this may seem trivial, simply using the RGB color model often yields non-accurate results for human perception. This is because RGB is not perceptually uniform.

Here is an example highlighting the limitations of using the RGB color model to compare colors.

As you can see, the difference between the two greens (left) is considered greater than the difference between the pink and gray colors (right). In other words, the pink and gray are considered to look more similar than the two greens.
This obviously does not match the expectation of the human eye.

Thankfully, ColorKit provides algorithms that make it possible to compare colors just like the human eye would: CIE76, CIE94 and CIEDE2000.

let colorDifference = UIColor.green.difference(from: .white, using: .CIE94) 

Here is the same example as above, using the CIE94 algorithm.

The CIE94 algorithm successfuly realizes that the two greens (left) look closer from each other than the pink and gray (right) do.

More information about color difference can be found here.


Contrast Ratio

To calculate the contrast ratio between two colors, simply use the contrastRatio function.

let contrastRatio = UIColor.green.contrastRatio(with: UIColor.white)

The contrast ratio is particularly important when displaying text. To ensure that it's readable by everyone, ColorKit makes it easy for you to follow the accessibility guidelines set by WCAG 2.


Color Space Conversions

ColorKit assists you when translating a color from a color space to another. They're simply supported as extensions on UIColor.
CIELAB, XYZ and CMYK are supported.


More

There is a lot more that ColorKit is capable of. Here is a short list of examples:

  • Working with Hex color codes
let hexValue = UIColor.green.hex
let color = UIColor(hex: "eb4034")
  • Generating random colors
let randomColor = UIColor.random()
  • Calculating the relative luminance of a color
let relativeLuminance = UIColor.green.relativeLuminance
  • Generating complementary colors
let complementaryColor = UIColor.green.complementaryColor

Installation

Swift Package Manager

The Swift Package Manager is the easiest way to install and manage ColorKit as a dependecy.
Simply add ColorKit to your dependencies in your Package.swift file:

dependencies: [
    .package(url: "https://github.com/Boris-Em/ColorKit.git")
]

Alternatively, you can also use XCode to add ColorKit to your existing project, by using File > Swift Packages > Add Package Dependency....

Manually

ColorKit can also be added to your project manually. Download the ColorKit project from Github, then drag and drop the folder ColorKit/ColorKit into your XCode project.


Sample Project

Use the iOS sample project included in this repository to find comprehensive examples of the different features of ColorKit.


Contributing

Contributions to ColorKit are always welcome!
For bugs and feature requests, open an issue.
To contribute to the code base, simply submit a pull request.


License

See the License. You are free to make changes and use this in either personal or commercial projects. Attribution is not required, but highly appreciated. A little "Thanks!" (or something to that affect) is always welcome. If you use ColorKit in one of your projects, please let us know!

Comments
  • EXC_BAD_ACCESS when using dominantColors() with default arguments

    EXC_BAD_ACCESS when using dominantColors() with default arguments

    When trying to fetch dominant colors from some images an exception is raised.

    Screen Shot 2022-04-21 at 09 57 23

    File: DominantColors.swift line 159

    This is the image that's causing crash IMG_3836

    In my code I just called the dominantColors() method with default arguments.

    opened by wiencheck 2
  • Bug on complimentaryColor() ?

    Bug on complimentaryColor() ?

    I think this might be a bug? Here's my code.

    let greenComp:UIColor = UIColor.green.complementaryColor //works let greenCompComp:UIColor = greenComp.complimentaryColor //error: value of type 'UIColor' has no member 'complimentaryColor'

    I know that UIColor does have member complimentaryColor cause it just used it in line 1. Not sure if I did something wrong.

    bug 
    opened by DandyLyons 2
  • Fixed crash related to unwrapping nil value when creating ColorPalette

    Fixed crash related to unwrapping nil value when creating ColorPalette

    With certain images the primary/backgroundColor values could not be obtained which led to crash when trying to unwrap those values.

    In such cases debugger prints such message: -[CIContext render:toBitmap:rowBytes:bounds:format:colorSpace:] unsupported colorspace.

    opened by wiencheck 1
  • kMeansClustering algorithm: Fatal error: Unexpectedly found nil while unwrapping an Optional value

    kMeansClustering algorithm: Fatal error: Unexpectedly found nil while unwrapping an Optional value

    Hey, first of all thanks for this amazing, impressive library.

    I'd like to report that when using .kMeansClustering algorithm, I often get a crash from unwrapping nil value. It happens at line 112 in file ColorPalette.swift

    The image I'm feeding to the algorithm is a transparent PNG (an asset file) so that's probably the cause of it. I know it doesn't make sense to pull colors from such image but the code should fail gracefully in such cases.

    opened by wiencheck 1
  • Task/actions checkout v3

    Task/actions checkout v3

    To fix the warning we get when running workflows: Node.js 12 actions are deprecated. For more information see: https://github.blog/changelog/2022-09-22-github-actions-all-actions-will-begin-running-on-node16-instead-of-node12/. Please update the following actions to use Node.js 16

    opened by roxannelandry 0
  • Add Localization Support for `name()` Function

    Add Localization Support for `name()` Function

    The name() function introduced recently was only supporting English. It is now setup to use Apple's localization system. This PR also adds the first localized language: French.

    Fixes #11.

    opened by Boris-Em 0
  • Localize Color Names

    Localize Color Names

    Via #10, we introduced a new function called name() that gives the English name of a UIColor instance.

    Localizing those names makes sense as a next step.

    enhancement 
    opened by Boris-Em 0
  • Add `name` function

    Add `name` function

    This commit simply adds a new function name() to UIColor instances via an extension. This function is useful to get a readable english name of the current color.

    Fixes #6.

    opened by Boris-Em 0
  • Added missing comma to README.md

    Added missing comma to README.md

    Expected

    let colors = try image.dominantColors()
    let palette = ColorPalette(orderedColors: colors, ignoreContrastRatio: true)
    

    Actual

    let colors = try image.dominantColors()
    let palette = ColorPalette(orderedColors: colors ignoreContrastRatio: true)
    
    opened by 0xLeif 0
  • Color Names for Accessibility

    Color Names for Accessibility

    A useful feature for accessibility is to be able to attach a readable color name to UIColor instances. For example UIColor.red or UIColor(red: 1.0, green: 0.0, blue: 0.0) should read something like "red".

    A trivial implementation of this could be to work with a predefined color palette and just compare it to the colors using the existing deltaE.

    enhancement good first issue 
    opened by Boris-Em 0
  • ColorKit, when using dominantColors(algorithm: .kMeansClustering) memory error

    ColorKit, when using dominantColors(algorithm: .kMeansClustering) memory error

    I'm using this function on each image of a video feed, and after a few seconds/tens of second, my program stops with this error, EXC_BAD_ACCESS (code=1, address=0xd833deece4d0). I assume it comes from this function and precisely kMeansClustering, because I don't encounter this issue using .iterative algorithm

    opened by Alexandre-BARBIER 3
  • I can't get dominant colors from pictures taken with iPhone

    I can't get dominant colors from pictures taken with iPhone

    Hello,

    first of all I wanted to say thank you for this awesome kit.

    I'm using ColorKit to generate a color palette of pictures that I manually add from my photo library. Everything work good but I only have problems with pictures of my library that were not taken with my iPhone.

    If I want to get the colors of pictures taken with my iPhone or a screenshot which was taken with my iPhone the function .dominantColors does not work.

    Is it a format thing? or maybe I missed something.

    If I send the picture per WhatsApp and then I download the same picture I can get the colors but not from the original. Photos taken with an external camera and then imported to the iPhone have also no problem at all. Only Iphone photos.

    I appreciate your help, thank you very much!

    Pablo.

    UPDATE I think that the problem is that ColorKit can't use .dominantColors() with pictures taken with the iPhone because they are HEIF/HEIC files. I still can't solve the problem but I'm trying to convert the image to JPEG. I don't know if that is useful because I thought UIImage also supports HEIF format.

    opened by papueh 3
  • Color Histogram

    Color Histogram

    Generating color histograms out of images.

    Here is some good resource from OpenCV as to what type of histogram we could generate as well as how to represent them.

    enhancement 
    opened by Boris-Em 0
Releases(v1.0.0)
Owner
Boris Emorine
Boris Emorine
Create complementary gradients generated from dominant and prominent colors in supplied image. Inspired by Grade.js

ComplimentaryGradientView Create complementary gradients generated from dominant and prominent colors in supplied image. Inspired by Grade.js ❤️ .all

George Kye 728 Dec 17, 2022
Read colors from Xcode assets file.

XcodePalette Read colors from Xcode assets file. How to Use Download the XcodePalette.Executable.zip of the latest release. Extract the XcodePalette U

iMoeNya 0 Nov 12, 2021
The repository for a command line / build pipeline tool for generating colors from a human-readable text file that designers can also use.

ColorPaletteGenerator ColorPaletteGenerator is a tool that takes a human-readable input file describing a color palette, and generates the associated

horseshoe7 0 Dec 7, 2021
Terminal Colors for Swift

Terminal string styling for Swift Colors is a clean and focused solution for string styling in Swift. Usage import Colors print(Colors.blue("Blue str

Paulo Tanaka 94 Sep 9, 2022
An Xcode plugin to improve dealing with colors in your project

Crayons is an Xcode7 plugin with various features that improve working with colors in your projects ##Code palettes (iOS only) You can share palettes

Fabio Ritrovato 477 Sep 23, 2022
TRex 🦖 TRex makes OCR easy and accessible on a Mac

TRex ?? TRex makes OCR easy and accessible on a Mac. But what is OCR anyway? Imagine you have a PDF file or a Web page where you can't select the text

Ameba Labs 700 Dec 23, 2022
iOS Framework that makes it easy to preview images on any UIImageView.

AZImagePreview iOS Framework that makes it easy to preview images on any UIImageView. Screenshots Installation: Cocoa Pods: pod 'AZImagePreview' Swift

Antonio Zaitoun 25 Dec 11, 2022
STDevRxExt contains some extension functions for RxSwift and RxCocoa which makes our live easy.

STDevRxExt Example To run the Example.playground, clone the repo, and run pod install from the Example directory first. Requirements iOS 9.0+ tvOS 9.0

STDev 6 Mar 26, 2021
📷 A composable image editor using Core Image and Metal.

Brightroom - Composable image editor - building your own UI Classic Image Editor PhotosCrop Face detection Masking component ?? v2.0.0-alpha now open!

Muukii 2.8k Jan 3, 2023
An image download extension of the image view written in Swift for iOS, tvOS and macOS.

Moa, an image downloader written in Swift for iOS, tvOS and macOS Moa is an image download library written in Swift. It allows to download and show an

Evgenii Neumerzhitckii 330 Sep 9, 2022
📷 A composable image editor using Core Image and Metal.

Brightroom - Composable image editor - building your own UI Classic Image Editor PhotosCrop Face detection Masking component ?? v2.0.0-alpha now open!

Muukii 2.8k Jan 2, 2023
AsyncImage before iOS 15. Lightweight, pure SwiftUI Image view, that displays an image downloaded from URL, with auxiliary views and local cache.

URLImage URLImage is a SwiftUI view that displays an image downloaded from provided URL. URLImage manages downloading remote image and caching it loca

Dmytro Anokhin 1k Jan 4, 2023
AYImageKit is a Swift Library for Async Image Downloading, Show Name's Initials and Can View image in Separate Screen.

AYImageKit AYImageKit is a Swift Library for Async Image Downloading. Features Async Image Downloading. Can Show Text Initials. Can have Custom Styles

Adnan Yousaf 11 Jan 10, 2022
A complete Mac App: drag an image file to the top section and the bottom section will show you the text of any QRCodes in the image.

QRDecode A complete Mac App: drag an image file to the top section and the bottom section will show you the text of any QRCodes in the image. QRDecode

David Phillip Oster 2 Oct 28, 2022
Convert the image to hexadecimal to send the image to e-paper

ConvertImageToHex Convert the image to hexadecimal to send the image to e-paper Conversion Order // 0. hex로 변환할 이미지 var image = UIImage(named: "sample

Hankyeol Park 0 Feb 26, 2022
Twitter Image Pipeline is a robust and performant image loading and caching framework for iOS clients

Twitter Image Pipeline (a.k.a. TIP) Background The Twitter Image Pipeline is a streamlined framework for fetching and storing images in an application

Twitter 1.8k Dec 17, 2022
Image-cropper - Image cropper for iOS

Image-cropper Example To run the example project, clone the repo, and run pod in

Song Vuthy 0 Jan 6, 2022
An instagram-like image editor that can apply preset filters passed to it and customized editings to a binded image.

CZImageEditor CZImageEditor is an instagram-like image editor with clean and intuitive UI. It is pure swift and can apply preset filters and customize

null 8 Dec 16, 2022
Lightbox is a convenient and easy to use image viewer for your iOS app

Lightbox is a convenient and easy to use image viewer for your iOS app, packed with all the features you expect: Paginated image slideshow. V

HyperRedink 1.5k Dec 22, 2022