PHP: 生成颜色,颜色处理,随机生产颜色,TinyColor,随机色彩,随机色系

项目地址:https://github.com/mistic100/RandomColor.php

下载 JS:randomColor.js

下载 PHP:RandomColor.php

 

Random Color

 

Options

You can pass an options object to influence the type of color it produces. The options object accepts the following properties:

hue – 控制颜色的色调,你可以输入色彩的颜色名称,例如:red, orange, yellow, green, blue, purple, pink 和 monochrome,也可以输入RGB的数字。Controls the hue of the generated color. You can pass a string representing a color name (e.g. ‘orange’). Possible color names are red, orange, yellow, green, blue, purple, pink and monochrome. You can also pass an array of multiple hues or a specific hue (0 to 360).

luminosity – 控制颜色的色彩光度,取值为:bright, light 或者 dark。 Controls the luminosity of the generated color. You can pass a string containing bright, light or dark.

format – 颜色的模式,取值为:hsv, hsl, hslCss, rgb, rgbCss, 和 hex。A string which specifies the format of the generated color. Possible values are hsv, hsl, hslCss, rgb, rgbCss, and hex.

prng – A random (or not) number generator. mt_rand is used as default one.

Examples

use \Colors\RandomColor;

// Returns a hex code for an attractive color
RandomColor::one(); 

// Returns an array of ten green colors
RandomColor::many(10, array(
   'hue' => 'green'
));

// Returns a hex code for a light blue
RandomColor::one(array(
   'luminosity' => 'light',
   'hue' => 'blue'
));

// Returns one yellow or blue color
RandomColors::one(array(
    'hue' => array('yellow', 'blue')
));

// Returns a hex code for a 'truly random' color
RandomColor::one(array(
   'luminosity' => 'random',
   'hue' => 'random'
));

// Returns a bright color in RGB
RandomColor::one(array(
   'luminosity' => 'bright',
   'format' => 'rgbCss' // e.g. 'rgb(225,200,20)'
));

DEMO

Examples

Once you have included RandomColor.class.php on your app, calling RandomColor::one($options) or RandomColor::many($count, $options) will return a random attractive color. Beneath is the live output of 36 generations.

RandomColor::many(36);

You can also pass an options object to randomColor. This allows you to specify the hue, luminosity and the format of colors to generate.

Format

RandomColor::one(array('format'=>'hex'));
  // "#58a308"

RandomColor::one(array('format'=>'hsv'));
  // array('h'=>89,'s'=>95,'v'=>64)

RandomColor::one(array('format'=>'hsl'));
  // array('h'=>89,'s'=>90.480000000000004,'l'=>33.600000000000001)

RandomColor::one(array('format'=>'rgb'));
  // array('r'=>88,'g'=>163,'b'=>8)

RandomColor::one(array('format'=>'hslCss'));
  // "hsl(89,90.48%,33.6%)"

RandomColor::one(array('format'=>'rgbCss'));
  // "rgb(88,163,8)"

Similar colors

RandomColor::many(18, array('hue'=>'red'));
RandomColor::many(18, array('hue'=>'orange'));
RandomColor::many(18, array('hue'=>'yellow'));
RandomColor::many(18, array('hue'=>'green'));
RandomColor::many(18, array('hue'=>'blue'));
RandomColor::many(18, array('hue'=>'purple'));
RandomColor::many(18, array('hue'=>'pink')); 
RandomColor::many(18, array('hue'=>'monochrome'));

Multiple colors

RandomColor::many(27, array('hue'=>array('blue', 'yellow')));

Light colors

RandomColor::many(27, array('luminosity'=>'light'));

Dark colors

RandomColor::many(27, array('luminosity'=>'dark'));

Truly random colors

RandomColor::many(36, array('luminosity'=>'random', 'hue'=>'random'));

Other languages

RandomColor is available in JavaScriptC#GoPythonSwiftObjective-CJava and R.

 

我个人不喜欢使用静态调用的方式,所以对php文件做了下面的修改:

使用方法:

$color = new Colors();

//Returns a hex code for an attractive color
$color->one();

// Returns an array of ten green colors
$color->many(10, array(
'hue' => 'green'
));

// Returns a hex code for a light blue
$color->one(array(
'luminosity' => 'light',
'hue' => 'blue'
));

// Returns one yellow or blue color
$color->one(array(
'hue' => array('yellow', 'blue')
));

// Returns a hex code for a 'truly random' color
$color->one(array(
'luminosity' => 'random',
'hue' => 'random'
));

// Returns a bright color in RGB
$color->one(array(
'luminosity' => 'bright',
'format' => 'rgbCss' // e.g. 'rgb(225,200,20)'
));

 

修改后的 RandomColor.php

<?php
defined('BASEPATH') or die('Restricted access');

/**
 * @filesource  :  colors.php
 * @Author      :  GLS
 * @copyright   :  Copyright (C) 2017-2018 GLS IT Studio SF
 * @access      :  gotodiscuss@gmail.com
 * @version     :  Created on Sep 25, 2017 7:12:08 PM
 *
 */
/**
 * RandomColor 1.0.3
 *
 * PHP port of David Merfield JavaScript randomColor
 * https://github.com/davidmerfield/randomColor
 *
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2014 Damien "Mistic" Sorel
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
class Colors
{
    /*
     * h=hueRange
     * s=saturationRange : bounds[0][0] ; bounds[-][0]
     */
    public $dictionary = array(
        'monochrome' => array(
            'bounds' => array(array(0,0), array(100,0)),
            'h' => NULL,
            's' => array(0,100)
        ),
        'red' => array(
            'bounds' => array(array(20,100),array(30,92),array(40,89),array(50,85),array(60,78),array(70,70),array(80,60),array(90,55),array(100,50)),
            'h' => array(-26,18),
            's' => array(20,100)
        ),
        'orange' => array(
            'bounds' => array(array(20,100),array(30,93),array(40,88),array(50,86),array(60,85),array(70,70),array(100,70)),
            'h' => array(19,46),
            's' => array(20,100)
        ),
        'yellow' => array(
            'bounds' => array(array(25,100),array(40,94),array(50,89),array(60,86),array(70,84),array(80,82),array(90,80),array(100,75)),
            'h' => array(47,62),
            's' => array(25,100)
        ),
        'green' => array(
            'bounds' => array(array(30,100),array(40,90),array(50,85),array(60,81),array(70,74),array(80,64),array(90,50),array(100,40)),
            'h' => array(63,178),
            's' => array(30,100)
        ),
        'blue' => array(
            'bounds' => array(array(20,100),array(30,86),array(40,80),array(50,74),array(60,60),array(70,52),array(80,44),array(90,39),array(100,35)),
            'h' => array(179,257),
            's' => array(20,100)
        ),
        'purple' => array(
            'bounds' => array(array(20,100),array(30,87),array(40,79),array(50,70),array(60,65),array(70,59),array(80,52),array(90,45),array(100,42)),
            'h' => array(258,282),
            's' => array(20,100)
        ),
        'pink' => array(
            'bounds' => array(array(20,100),array(30,90),array(40,86),array(60,84),array(80,80),array(90,75),array(100,73)),
            'h' => array(283,334),
            's' => array(20,100)
        )
    );

    function __construct() { }

    public function one($options = array())
    {
        $h = $this->_pickHue($options);
        $s = $this->_pickSaturation($h, $options);
        $v = $this->_pickBrightness($h, $s, $options);

        return $this->format(compact('h','s','v'), @$options['format']);
    }

    public function many($count, $options = array())
    {
        $colors = array();
        for ($i = 0; $i < $count; $i++) $colors[] = $this->one($options);
        return $colors;
    }

    public function format($hsv, $format='hex')
    {
        switch ($format)
        {
            case 'hsv':    return $hsv;
            case 'hsl':    return $this->hsv2hsl($hsv);
            case 'hslCss': $hsl = $this->hsv2hsl($hsv); return 'hsl(' . $hsl['h'] . ',' . $hsl['s'] . '%,' . $hsl['l'] . '%)';
            case 'rgb':    return $this->hsv2rgb($hsv);
            case 'rgbCss': return 'rgb(' . implode(',', $this->hsv2rgb($hsv)) . ')';
            case 'hex':
            default:       return $this->hsv2hex($hsv);
        }
    }

    private function _pickHue($options)
    {
        $range = $this->_getHueRange($options);

        if (empty($range)) return 0;

        $hue = $this->_rand($range, $options);

        // Instead of storing red as two separate ranges,
        // we group them, using negative numbers
        if ($hue < 0) $hue = 360 + $hue;

        return $hue;
    }

    private function _pickSaturation($h, $options)
    {
        if (@$options['luminosity'] === 'random') return $this->_rand(array(0, 100), $options);
        if (@$options['hue'] === 'monochrome') return 0;

        $colorInfo = $this->_getColorInfo($h);
        $range = $colorInfo['s'];

        switch (@$options['luminosity'])
        {
            case 'bright': $range[0] = 55; break;
            case 'dark': $range[0] = $range[1] - 10; break;
            case 'light': $range[1] = 55; break;
        }

        return $this->_rand($range, $options);
    }

    private function _pickBrightness($h, $s, $options)
    {
        if (@$options['luminosity'] === 'random') $range = array(0, 100);
        else
        {
            $range = array( $this->_getMinimumBrightness($h, $s), 100 );

            switch (@$options['luminosity'])
            {
                case 'dark':  $range[1] = $range[0] + 20;              break;
                case 'light': $range[0] = ($range[1] + $range[0]) / 2; break;
            }
        }

        return $this->_rand($range, $options);
    }

    private function _getHueRange($options)
    {
        $ranges = array();

        if (isset($options['hue']))
        {
            if (!is_array($options['hue'])) $options['hue'] = array($options['hue']);

            foreach ($options['hue'] as $hue)
            {
                if ($hue === 'random') $ranges[] = array(0, 360);
                else if (isset($this->dictionary[$hue])) $ranges[] = $this->dictionary[$hue]['h'];
                else if (is_numeric($hue))
                {
                    $hue = intval($hue);
                    if ($hue <= 360 && $hue >= 0) $ranges[] = array($hue, $hue);
                }
            }
        }

        if (($l = count($ranges)) === 0) return array(0, 360);
        else if ($l === 1) return $ranges[0];
        else return $ranges[$this->_rand(array(0, $l-1), $options)];
    }

    private function _getMinimumBrightness($h, $s)
    {
        $colorInfo = $this->_getColorInfo($h);
        $bounds = $colorInfo['bounds'];

        for ($i = 0, $l = count($bounds); $i < $l - 1; $i++)
        {
            $s1 = $bounds[$i][0];
            $v1 = $bounds[$i][1];
            $s2 = $bounds[$i+1][0];
            $v2 = $bounds[$i+1][1];

            if ($s >= $s1 && $s <= $s2)
            {
                $m = ($v2 - $v1) / ($s2 - $s1);
                $b = $v1 - $m * $s1;
                return $m * $s + $b;
            }
        }

        return 0;
    }

    private function _getColorInfo($h)
    {
        // Maps red colors to make picking hue easier
        if ($h >= 334 && $h <= 360) $h-= 360;
        foreach ($this->dictionary as $color) if ($color['h'] !== null && $h >= $color['h'][0] && $h <= $color['h'][1]) return $color;
    }

    private function _rand($bounds, $options)
    {
        return isset($options['prng']) ? $options['prng']($bounds[0], $bounds[1]) : mt_rand($bounds[0], $bounds[1]);
    }

    public function hsv2hex($hsv)
    {
        $rgb = $this->hsv2rgb($hsv);
        $hex = '#';

        foreach ($rgb as $c) $hex.= str_pad(dechex($c), 2, '0', STR_PAD_LEFT);

        return $hex;
    }

    public function hsv2hsl($hsv)
    {
        extract($hsv);

        $s/= 100;
        $v/= 100;
        $k = (2-$s)*$v;

        return array( 'h' => $h, 's' => round($s*$v / ($k < 1 ? $k : 2-$k), 4) * 100, 'l' => $k/2 * 100, );
    }

    public function hsv2rgb($hsv)
    {
        extract($hsv);

        $h/= 360;
        $s/= 100;
        $v/= 100;

        $i = floor($h * 6);
        $f = $h * 6 - $i;

        $m = $v * (1 - $s);
        $n = $v * (1 - $s * $f);
        $k = $v * (1 - $s * (1 - $f));

        $r = 1;
        $g = 1;
        $b = 1;

        switch ($i)
        {
            case 0: list($r,$g,$b) = array($v,$k,$m); break;
            case 1: list($r,$g,$b) = array($n,$v,$m); break;
            case 2: list($r,$g,$b) = array($m,$v,$k); break;
            case 3: list($r,$g,$b) = array($m,$n,$v); break;
            case 4: list($r,$g,$b) = array($k,$m,$v); break;
            case 5:
            case 6: list($r,$g,$b) = array($v,$m,$n); break;
        }

        return array( 'r' => floor($r*255), 'g' => floor($g*255), 'b' => floor($b*255), );
    }
}

 

JS 用法

var color = randomColor(); // a hex code for an attractive color

Options

You can pass an options object to influence the type of color it produces. The options object accepts the following properties:

hue – Controls the hue of the generated color. You can pass a string representing a color name: redorangeyellowgreenbluepurplepink and monochrome are currently supported. If you pass a hexidecimal color string such as #00FFFF, randomColor will extract its hue value and use that to generate colors.

luminosity – Controls the luminosity of the generated color. You can specify a string containing brightlight or dark.

count – An integer which specifies the number of colors to generate.

seed – An integer or string which when passed will cause randomColor to return the same color each time.

format – A string which specifies the format of the generated color. Possible values are rgbrgbargbArrayhslhslahslArray and hex (default).

alpha – A decimal between 0 and 1. Only relevant when using a format with an alpha channel (rgba and hsla). Defaults to a random value.

Examples

// Returns a hex code for an attractive color
randomColor(); 

// Returns an array of ten green colors
randomColor({
   count: 10,
   hue: 'green'
});

// Returns a hex code for a light blue
randomColor({
   luminosity: 'light',
   hue: 'blue'
});

// Returns a hex code for a 'truly random' color
randomColor({
   luminosity: 'random',
   hue: 'random'
});

// Returns a bright color in RGB
randomColor({
   luminosity: 'bright',
   format: 'rgb' // e.g. 'rgb(225,200,20)'
});

// Returns a dark RGB color with random alpha
randomColor({
   luminosity: 'dark',
   format: 'rgba' // e.g. 'rgba(9, 1, 107, 0.6482447960879654)'
});

// Returns a dark RGB color with specified alpha
randomColor({
   luminosity: 'dark',
   format: 'rgba',
   alpha: 0.5 // e.g. 'rgba(9, 1, 107, 0.5)',
});

// Returns a light HSL color with random alpha
randomColor({
   luminosity: 'light',
   format: 'hsla' // e.g. 'hsla(27, 88.99%, 81.83%, 0.6450211517512798)'
});

本文:PHP: 生成颜色,颜色处理,随机生产颜色,TinyColor,随机色彩,随机色系

Loading

Add a Comment

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.