ColorExtractor: 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

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); ">
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
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
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
PHP Image Manipulation

Intervention Image Intervention Image is a PHP image handling and manipulation library providing an easier and expressive way to create, edit, and com

null 13k Jan 3, 2023
PHP 5.3 Object Oriented image manipulation library

Imagine Tweet about it using the #php_imagine hashtag. Image manipulation library for PHP 5.3 inspired by Python's PIL and other image libraries. Requ

Bulat Shakirzyanov 4.3k Jan 6, 2023
Wonderfully easy on-demand image manipulation library with an HTTP based API.

Glide Glide is a wonderfully easy on-demand image manipulation library written in PHP. Its straightforward API is exposed via HTTP, similar to cloud i

The League of Extraordinary Packages 2.4k Dec 19, 2022
🌄 Perceptual image hashing for PHP

ImageHash A perceptual hash is a fingerprint of a multimedia file derived from various features from its content. Unlike cryptographic hash functions

Jens Segers 1.9k Dec 28, 2022
Image optimization / compression library. This library is able to optimize png, jpg and gif files in very easy and handy way. It uses optipng, pngquant, pngcrush, pngout, gifsicle, jpegoptim and jpegtran tools.

Image Optimizer This library is handy and very easy to use optimizer for image files. It uses optipng, pngquant, jpegoptim, svgo and few more librarie

Piotr Śliwa 879 Dec 30, 2022
:racehorse: find the size of an image without downloading the whole file. Supports batch requests.

FasterImage FasterImage finds the dimensions or filetype of a remote image file given its uri by fetching as little as needed, based on the excellent

Will Washburn 58 Nov 30, 2022
php-gd based image templates

gdaisy A highly experimental image templating system based on PHP-GD to dynamically generate image banners and covers. Installation 1. Require erikahe

Erika Heidi 67 Nov 22, 2022
An open source image hosting service powered by Laravel

Limg An open source image hosting service powered by Laravel Features Upload your image via file, url or ShareX ! Manage your image (custom title, pub

Thomas 56 Dec 16, 2022
A simple page view counter that store data as text and shows data as a PNG image

Image Counter A simple page view counter that store data as text and shows the counter as a PNG image.

Victor Ribeiro 10 Apr 19, 2022
Grabs the dominant color or a representative color palette from an image. Uses PHP and GD, Imagick or Gmagick.

Color Thief PHP A PHP class for grabbing the color palette from an image. Uses PHP and GD or Imagick libraries to make it happen. It's a PHP port of t

Kevin Subileau 610 Dec 28, 2022
PHP library to easily edit image with GD extension. Resize, crop, merge, draw, and many more options !

PHP Image Editor PHP library to easily edit image with GD extension. Resize, crop, merge, draw, and many more options ! ✨ Supporting ⭐ Star this repos

Franck Alary 17 Nov 13, 2022
image sharing site made in PHP just for fun and freetime

2bart image sharing site made in PHP just for fun and freetime To-do list: upload system [DONE] ✔️ views system [DONE] ✔️ image list system [DONE] ✔️

goom 1 Oct 22, 2021
Convert image types. Take samples of pdfs or psd, do some filters as SEPIA, resizes. Save to WEBP

img2img. PHP Converter, sampler of pdfs & psd, do resizes & some filters in images as SEPIA. Save to WEBP V.1.0.3 This class in pure PHP try to manage

Rafael Martin Soto 9 Oct 23, 2022
Alternative image provider for fakerphp using picsum.photos

Fakerphp Picsum Images Introduction Alternative image provider for fakerphp using picsum.photos This package has been forked from mmo/faker-images for

Arnaud Becher 16 Dec 9, 2022
Picasso is a Laravel Image Management and Optimization Package

Picasso is a Laravel Image Management and Optimization Package. Define image dimensions and options, store uploaded image in multiple dimensions with or without a watermark and retrieve optimized images on your website when needed.

Laravelista 82 Nov 24, 2022