Extract colors from an image like a human would do.

Overview

ColorExtractor

Build Status Total Downloads Latest Stable Version

Extract colors from an image like a human would do.

Install

Via Composer

$ composer require league/color-extractor:0.3.*

Usage

require 'vendor/autoload.php';

use League\ColorExtractor\Color;
use League\ColorExtractor\ColorExtractor;
use League\ColorExtractor\Palette;

$palette = Palette::fromFilename('./some/image.png');

// $palette is an iterator on colors sorted by pixel count
foreach($palette as $color => $count) {
    // colors are represented by integers
    echo Color::fromIntToHex($color), ': ', $count, "\n";
}

// it offers some helpers too
$topFive = $palette->getMostUsedColors(5);

$colorCount = count($palette);

$blackCount = $palette->getColorCount(Color::fromHexToInt('#000000'));


// an extractor is built from a palette
$extractor = new ColorExtractor($palette);

// it defines an extract method which return the most “representative” colors
$colors = $extractor->extract(5);

Handling transparency

By default any pixel with alpha value greater than zero will be discarded. This is because transparent colors are not perceived as is. For example fully transparent black would be seen white on a white background. So if you want to take transparency into account when building a palette you have to specify this background color. You can do this with the second argument of Palette constructors. Its default value is null, meaning a color won't be added to the palette if its alpha component exists and is greater than zero.

You can set it as an integer representing the color, then transparent colors will be blended before addition to the palette.

// we set a white background so fully transparent colors will be added as white in the palette
// pure red #FF0000 at 50% opacity will be stored as #FF8080 as it would be perceived
$palette = Palette::fromFilename('./some/image.png', Color::fromHexToInt('#FFFFFF'));

Contributing

Please see CONTRIBUTING for details.

Credits

License

The MIT License (MIT). Please see License File for more information.

Comments
  • 0.2.0

    0.2.0

    Considering #17 I think it would be interesting to allow the Image class to offer any color-related functionality. For now we just have the implicit extract method which prevents consistency, it certainly means there will be some BC.

    Any idea of how to do that properly?

    opened by MatTheCat 23
  • Alpha channel of .png is taken into account

    Alpha channel of .png is taken into account

    Hello and congratulations for this nice piece of code !

    I am trying to work with some .png files and this one particularly fails and returns me #000000 as the most vibrant color. capture d ecran 2016-03-17 a 20 38 32

    I guess it fetches it from the alpha channel.

    Could you have a more in-depth look please ? Here is the image interval_contentsc

    opened by RomainSauvaire 15
  • Infinite loop in while from Image.php

    Infinite loop in while from Image.php

    Hi,

    Got an infinite loop on ligne 129 of Image.php for some images. Image size is 50*50.

    As you can see on my PR, this https://github.com/thephpleague/color-extractor/pull/25 fix the thing.

    Any idea ?

    Thx

    opened by brunonic 9
  • Extract stuck in an infinite loop

    Extract stuck in an infinite loop

    I have found an issue when I try and extract colours from corrupted images, the extract method seems to get stuck in a loop and eventually times out.

    I have attached a faulty image, hopefully it will survive intact. xhtrlexhqkqy

    opened by ArthurGuy 8
  • BadMethodException thrown for use of undefined method [package] in Laravel 5

    BadMethodException thrown for use of undefined method [package] in Laravel 5

    Issue: In laravel 5 when the ServiceProvider is loaded it throws BadMethodCallException for use of undefined method [package].

    Fix: Commenting out the boot() section of the ServiceProvider works fine.

    opened by ajaaibu 7
  • add Imagick support

    add Imagick support

    Fix #37

    Add creation method for Imagick and call it from fromFilename if the extension is loaded because it seems faster.

    Since ext-gd is no longer mandatory I moved it with ext-imagick in composer.json suggest section.

    I'm thinking this PR could introduce the 1.0.0 release. What do you think @GrahamCampbell @philsturgeon @toin0u?

    opened by MatTheCat 6
  • Update readme to mention GD support requirement

    Update readme to mention GD support requirement

    I had issues trying to use this library initially, because I didn't realize it was using GD manipulations under the hood, and by default my (and possibly most) php installations don't include GD support out of the box.

    I found the documentation and comments at http://php.net/manual/en/image.installation.php helpful in order to install php5-gd on my debian-based distro in order to use this library.

    Without GD support, errors occur such as:

    Call to undefined function League\ColorExtractor\imagecreatefrompng() in [...]/vendor/league/color-extractor/src/League/ColorExtractor/Client.php on line 14
    

    In order to help others, I submit this README.md update comment referencing the php.net documentation.

    opened by glasnt 4
  • PHP 8.1.5 GD image resources bug?

    PHP 8.1.5 GD image resources bug?

    Hey guys,

    I am doing some tutorials on composer and one of the lessons uses the color-extractor package. All seems to install ok. But I keep getting an error when I try to stream in an image.

    This code block seems to cause an issue (line 54-55 - vendor/league/color-extractor/src/League/ColorExtractor/Palette.php): $image = imagecreatefromstring(file_get_contents($filename)); $palette = self::fromGD($image, $backgroundColor);

    As does this one (line 71 same file): if (!is_resource($image) || get_resource_type($image) != 'gd')

    The condition gets met and we see the following error.

    Fatal error: Uncaught InvalidArgumentException: Image must be a gd resource in /Users/ufmurphy/Sites/vendor/league/color-extractor/src/League/ColorExtractor/Palette.php:72 Stack trace: #0 /Users/ufmurphy/Sites/vendor/league/color-extractor/src/League/ColorExtractor/Palette.php(55): League\ColorExtractor\Palette::fromGD(Object(GdImage), NULL) #1 /Users/ufmurphy/Sites/index.php(19): League\ColorExtractor\Palette::fromFilename('images/bricks.j...') #2 {main} thrown in /Users/ufmurphy/Sites/vendor/league/color-extractor/src/League/ColorExtractor/Palette.php on line 72

    Doing some sleuthing, it looks like a change in how GD images are handled in PHP8. https://php.watch/versions/8.0/gdimage

    Is there a more recent version than 0.3.2?

    Thanks, Jim

    opened by UFMurphy 3
  • question: is over 1gb of memory usage normal?

    question: is over 1gb of memory usage normal?

    php memory limit is 1024 MB, the below exception occurs while processing a 12 MB jpeg. I can of course increase the memory limit, but wondered if this level of memory usage is expected?

    PHP Fatal error:  Allowed memory size of 1073741824 bytes exhausted (tried to allocate 20480 bytes) in /var/www/auto/vendor/league/color-extractor/src/League/ColorExtractor/ColorExtractor.php on line 226
    PHP Fatal error:  Allowed memory size of 1073741824 bytes exhausted (tried to allocate 20480 bytes) in /var/www/auto/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php on line 122
    

    Here's my color extraction code:

    $primaryPalette = Palette::fromFilename($sFullPath);
    $extractor = new ColorExtractor($primaryPalette);
    $primaryPalette = null;
    
    $aExtractedColours = $extractor->extract(5);
    $extractor = null;
    
    opened by samthomson 3
  • PHP8 support

    PHP8 support

    Hi, I'm getting an "Image must be a gd resource"

    PHP has moved to make GD an object instead of a resource, because GD is now an object, it will never be a resource and this causes an error

    opened by malanx 3
  • Better Palette generation

    Better Palette generation

    I love the interface of this package. However, the palette that it generates contains the color value of every pixel it seems, even if the colors are nearly indistinguishable. I would love to be able to find the 5 most used colors that are actually in different color spectrums instead of 5 colors that are practically the same color.

    I have been using this package to find a good color palette https://github.com/ksubileau/color-thief-php but its interface is not quite as nice as this one.

    opened by joeworkman 3
  • Palette.getMostUsedColors() getting different values depending on OS / PHP version

    Palette.getMostUsedColors() getting different values depending on OS / PHP version

    Hi, I just started to use color-extractor in one or our customer's project.

    We wrote a unit test to check our code and it appears the Palette.getMostUsedColors() function is not returning de same results depending on the OS and/or PHP version in use (perhaps this could also be dependent on the GD version which is installed on the machine).

    For exemple on a Unix machine we get this array (the limit parameter is equal to 12 and the index of this array has been converted to hexadecimal).

    [
        '#000000' => 93285,
        '#010000' => 7871,
        '#020001' => 6022,
        '#010101' => 3413,
        '#040000' => 3321,
        '#000002' => 2070,
        '#050100' => 2036,
        '#030000' => 1945,
        '#000100' => 1789,
        '#060000' => 1668,
        '#020100' => 1604,
        '#634D40' => 1263,
    ]
    

    On a Windows machine and with the same image we get the following values.

    [
        '#000000' => 93135,
        '#010000' => 7710,
        '#020001' => 6001,
        '#010101' => 3377,
        '#040000' => 3227,
        '#000002' => 2056,
        '#050100' => 2052,
        '#000100' => 1842,
        '#030000' => 1747,
        '#020100' => 1580,
        '#060000' => 1557,
        '#634D40' => 1264,
    ]
    

    We only encounter this problem with one testing JPEG file (I can provide you the file if needed).

    We also have similar unit test with GIF and PNG files, with those formats we do not encounter any problem.

    So do you know what could cause differences in our case ?

    • Could it be caused by the GD version installed on the machine ? Also perhaps their are difference between the Windows and Unix GD libraries ?
    • Could it be caused by the PHP version in use ?
    • Or are they potential rounded values in the source code which could be different between platforms ?

    If it can help here are much more details about each testing envirronment

    • Windows 10 Pro 64bits, PHP 7.0.8
    • Centos 7 64bits, PHP 7.0.8

    If the problem is linked to GD perhaps doing the same test with https://github.com/thephpleague/color-extractor/issues/37 could be interesting.

    In any case I the problem cannot be solved IMO it should be described and explained in the README.

    Thanks

    opened by bgaillard 7
  • Palette::fromImagick()

    Palette::fromImagick()

    Hello

    Here is a proposition for Imagick integration in Palette.

    
    
        /**
         * @param \Imagick $image
         *
         * @return Palette
         *
         * @throws \InvalidArgumentException
         */
        public static function fromImagick(\Imagick $image)
        {
            if (!is_object($image) || $image instanceof \Imagick === FALSE) {
                throw new \InvalidArgumentException('Image must be an Imagick instance');
            }
    
            $palette = new self();
            $palette->colors = [];
    
            $iterator = $image->getPixelIterator();
    
            foreach($iterator as $row) {
    
                foreach($row as $pixel) {
    
                    $colorInfo = $pixel->getColor();
                    $color = ($colorInfo['r'] * 65536) + ($colorInfo['g'] * 256) + ($colorInfo['b']);
    
                    isset($palette->colors[$color]) ?
                        $palette->colors[$color] += 1 :
                        $palette->colors[$color] = 1;
    
                }
    
            }
    
            arsort($palette->colors);
    
            return $palette;
        }
    
    opened by vingtcent123 2
Releases(0.4.0)
  • 0.4.0(Sep 24, 2022)

    Added

    • Added support for PHP 8.x
    • Added new Palette::fromUrl() method with optional support for curl
    • Added new Palette::fromContents() method
    • Added return types to Palette::count() and Palette:getIterator()

    Changed

    • Palette::fromFilename() now throws InvalidArgumentException if the target file doesn't exist or can't be read

    Fixed

    • Fixed Palette:getColorCount() erroring when the given color doesn't exist in the image
    • Fixed ColorExtractor erroring when no interesting colors exist

    Removed

    • Dropped support for PHP <= 7.2
    Source code(tar.gz)
    Source code(zip)
Owner
The League of Extraordinary Packages
A group of developers who have banded together to build solid, well tested PHP packages using modern coding standards.
The League of Extraordinary Packages
Extract colors from an image like a human would do.

ColorExtractor Extract colors from an image like a human would do. Install Via Composer $ composer require league/color-extractor:0.3.* Usage require

The League of Extraordinary Packages 1.2k Jan 1, 2023
ColorExtractor: Extract colors from an image like a human would do

ColorExtractor Extract colors from an image like a human would do. Install Via Composer $ composer require league/color-extractor:0.3.* Usage require

The League of Extraordinary Packages 1.2k Jan 3, 2023
Image Cache is a very simple PHP class that accepts an image source and will compress and cache the file, move it to a new directory, and returns the new source for the image.

NO LONGER MAINTAINED!!! Image Cache v. 1.0.0 Image Cache is a very simple PHP class that accepts an image source and will compress and cache the file,

Erik Nielsen 455 Dec 30, 2022
SlimJim was born out of a need for a simple auto update script which would update multiple development/test environments every time someone

SlimJim WHY? SlimJim was born out of a need for a simple auto update script which would update multiple development/test environments every time someo

Jesal Gadhia 100 Apr 22, 2022
ColorJizz is a PHP library for manipulating and converting colors.

#Getting started: ColorJizz-PHP uses the PSR-0 standards for namespaces, so there should be no trouble using with frameworks like Symfony 2. ###Autolo

Mikeemoo 281 Nov 25, 2022
An easy way to add colors in your CLI scripts.

COLORS Here is a preview of what you can achieve with the library: Installation Installation via composer is highly recommended. { "require": {

Kevin Le Brun 335 Dec 4, 2022
A series of methods that let you manipulate colors. Just incase you ever need different shades of one color on the fly.

PHPColors A series of methods that let you manipulate colors. Just incase you ever need different shades of one color on the fly. Requirements PHPColo

Arlo Carreon 423 Dec 20, 2022
Magento 2 Grid Colors module for colorizing admin grids. Supports saving of states with the help of grid's bookmarks.

Magento 2 Grid Colors Overview The module adds extra coloring features to admin grids at the Sales section. With help of this module, it is possible t

Dmitry Shkoliar 58 Dec 8, 2022
A PocketMine-MP Plugin that allow you to change your nickname to specific colors

General Home A PocketMine-MP Plugin that allow you to change your display nametag to specific colors Made By BabosApple And Updated To PM4 By ZhorifCr

ZhorifCraft451 0 Feb 22, 2022
Auto Image & file upload, resize and crop for Laravel eloquent model using Intervention image

Laravel ImageUp The qcod/laravel-imageup is a trait which gives you auto upload, resize and crop for image feature with tons of customization. Install

QCode.in 708 Dec 22, 2022
A Laravel Gravatar package for retrieving gravatar image URLs or checking the existance of an image.

Gravatar for Laravel 5.x, 6, 7 and 8 Installation First, pull in the package through Composer via the command line: composer require creativeorange/gr

Creativeorange 477 Dec 1, 2022
This plugin adds a new image style for the Core Image block.

This plugin adds a new image style for the Core Image block. Introduction How to use? Go to Gutenberg Editor and add a image block. e.g. Add new image

Mahesh Waghmare 3 Feb 17, 2022
WordPress plugin renames image filenames to be more SEO friendly, based on the post's data and image metadata.

=== Automatic image Rename === Contributors: wpsunshine Tags: image, images, SEO, rename, optimization Requires at least: 5.0 Tested up to: 6.2.2 Stab

null 8 Jun 11, 2023
Blackfire Player is a powerful Web Crawling, Web Testing, and Web Scraper application. It provides a nice DSL to crawl HTTP services, assert responses, and extract data from HTML/XML/JSON responses.

Blackfire Player Blackfire Player is a powerful Web Crawling, Web Testing, and Web Scraper application. It provides a nice DSL to crawl HTTP services,

Blackfire 485 Dec 31, 2022
PdfParser, a standalone PHP library, provides various tools to extract data from a PDF file.

PdfParser Pdf Parser, a standalone PHP library, provides various tools to extract data from a PDF file. Website : https://www.pdfparser.org Test the A

Sebastien MALOT 1.9k Jan 2, 2023
Extract SQL statements from migrations

This is my package MigrationToSql To install: composer require bcleverly/migrationtosql --dev This repo is here to help you extract the SQL queries fr

Ben 4 Apr 15, 2022
A tiny PHP class-based program to analyze an input file and extract all of that words and detect how many times every word is repeated

A tiny PHP class-based program to analyze an input file and extract all of that words and detect how many times every word is repeated

Max Base 4 Feb 22, 2022
Extract and evolution of the magento2-currency-precision module from the magento2-jp project from @Magento

Currency Precision Module for Magento 2 This module aims to help merchants to manage easily their currency precision in Magento 2. DISCLAIMER Initiall

OpenGento 3 Dec 17, 2021
Declaratively specify how to extract elements from a JSON document, in PHP

jmespath.php JMESPath (pronounced "jaymz path") allows you to declaratively specify how to extract elements from a JSON document. jmespath.php allows

null 1.7k Dec 30, 2022