PHP code example of farzai / color-palette

1. Go to this page and download the library: Download farzai/color-palette library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

farzai / color-palette example snippets


use Farzai\ColorPalette\ColorPalette;

$palette = ColorPalette::fromImage('path/to/image.jpg', 5);
$colors = $palette->toArray();
// Result: ['#ff5733', '#33ff57', '#5733ff', '#f4a460', '#8b4513']

use Farzai\ColorPalette\ColorPalette;
use Farzai\ColorPalette\Color;

// Extract from image
$palette = ColorPalette::builder()
    ->fromImage('path/to/image.jpg')
    ->withCount(8)
    ->build();

// Generate from a base color
$palette = ColorPalette::builder()
    ->withBaseColor(Color::fromHex('#3498db'))
    ->withScheme('monochromatic', ['count' => 7])
    ->build();

use Farzai\ColorPalette\ImageFactory;
use Farzai\ColorPalette\ColorExtractorFactory;

// Static methods
$image = ImageFactory::fromPath('path/to/image.jpg');
$extractor = ColorExtractorFactory::gd();
$palette = $extractor->extract($image, 5);

// Instance methods with dependencies
$extractor = (new ColorExtractorFactory($logger))->make('gd');
$palette = $extractor->extract($image, 5);

// Simple static method
$image = ImageFactory::fromPath('photo.jpg');

// Specify driver (gd or imagick)
$image = ImageFactory::fromPath('photo.jpg', 'imagick');

// Simple static methods
$extractor = ColorExtractorFactory::gd();
$extractor = ColorExtractorFactory::imagick();

$palette = ColorPalette::fromImage('photo.jpg', 5);

// Access colors
$colors = $palette->toArray();     // Returns ['#ff5733', ...]
$firstColor = $palette[0];         // Array access
$count = count($palette);          // Countable

$color = Color::fromHex('#ff5733');

// Manipulation returns NEW color objects
$lighter = $color->lighten(0.2);
$darker = $color->darken(0.3);

use Farzai\ColorPalette\ColorPalette;

// Extract colors from logo
$palette = ColorPalette::fromImage('assets/logo.png', 8);

// Get suggested theme colors
$theme = $palette->getSuggestedSurfaceColors();

echo "Surface: " . $theme['surface']->toHex();       // #f5f5f5
echo "Background: " . $theme['background']->toHex(); // #e8e8e8
echo "Accent: " . $theme['accent']->toHex();         // #ff5733

// Get appropriate text colors
$textOnSurface = $palette->getSuggestedTextColor($theme['surface']);
$textOnAccent = $palette->getSuggestedTextColor($theme['accent']);

use Farzai\ColorPalette\Color;

$background = Color::fromHex('#ffffff');
$primary = Color::fromHex('#1976d2');

// Check contrast ratio
$ratio = $background->getContrastRatio($primary);
echo "Contrast Ratio: {$ratio}:1\n";

// Validate WCAG compliance
if ($ratio >= 7.0) {
    echo "PASS: WCAG AAA - Normal Text\n";
} elseif ($ratio >= 4.5) {
    echo "PASS: WCAG AA - Normal Text\n";
} elseif ($ratio >= 3.0) {
    echo "PASS: WCAG AA - Large Text\n";
} else {
    echo "FAIL: Does not meet WCAG standards\n";

    // Automatically adjust for compliance
    $adjustedPrimary = $primary->darken(0.2);
    $newRatio = $background->getContrastRatio($adjustedPrimary);
    echo "Adjusted Color: " . $adjustedPrimary->toHex() . "\n";
    echo "New Ratio: {$newRatio}:1\n";
}

use Farzai\ColorPalette\ColorPalette;

$palette = ColorPalette::fromImage('hero-image.jpg', 6);

echo ":root {\n";
foreach ($palette->getColors() as $index => $color) {
    $hex = $color->toHex();
    $rgb = $color->toRgb();

    echo "  --color-{$index}: {$hex};\n";
    echo "  --color-{$index}-rgb: {$rgb['r']}, {$rgb['g']}, {$rgb['b']};\n";
}
echo "}\n";

// Output:
// :root {
//   --color-0: #ff5733;
//   --color-0-rgb: 255, 87, 51;
//   --color-1: #33ff57;
//   --color-1-rgb: 51, 255, 87;
//   ...
// }

use Farzai\ColorPalette\ColorPalette;
use Farzai\ColorPalette\Color;

$brandColor = Color::fromHex('#3498db');

// Automatic scheme generation
$complementary = ColorPalette::fromColor($brandColor, 'complementary');
$triadic = ColorPalette::fromColor($brandColor, 'triadic');
$monochromatic = ColorPalette::fromColor($brandColor, 'monochromatic', ['count' => 7]);

// Manual color manipulation
$lighter = $brandColor->lighten(0.2);
$darker = $brandColor->darken(0.2);
$rotated = $brandColor->rotate(180);  // Complementary

$palette = ColorPalette::fromImage('photo.jpg', 5);

// Static method
$image = ImageFactory::fromPath('photo.jpg', 'gd');

// Instance method (for dependency injection)
$factory = new ImageFactory($extensionChecker);
$image = $factory->createFromPath('photo.jpg');

$palette = ColorPalette::fromImage('photo.jpg', 5);

// Static methods
$extractor = ColorExtractorFactory::gd();
$extractor = ColorExtractorFactory::imagick();

// Extract colors
$palette = $extractor->extract($image, 5);

// From different formats
$color = Color::fromHex('#ff5733');                          // Hex string (with or without #)
$color = Color::fromRgb(['r' => 255, 'g' => 87, 'b' => 51]); // RGB array (or numeric: [255, 87, 51])
$color = Color::fromHsl(9, 100, 60);                         // HSL values (h: 0-360, s/l: 0-100)
$color = Color::fromHsv(9, 80, 100);                         // HSV values (h: 0-360, s/v: 0-100)
$color = Color::fromCmyk(0, 66, 80, 0);                      // CMYK values (0-100)
$color = Color::fromLab(62, 52, 51);                         // LAB values (l: 0-100, a/b: -128 to 127)

$hex = $color->toHex();    // Returns: '#ff5733'
$rgb = $color->toRgb();    // Returns: ['r' => 255, 'g' => 87, 'b' => 51]
$hsl = $color->toHsl();    // Returns: ['h' => 9, 's' => 100, 'l' => 60]
$hsv = $color->toHsv();    // Returns: ['h' => 9, 's' => 80, 'v' => 100]
$cmyk = $color->toCmyk();  // Returns: ['c' => 0, 'm' => 66, 'y' => 80, 'k' => 0]
$lab = $color->toLab();    // Returns: ['l' => 62, 'a' => 52, 'b' => 51]

$color = Color::fromHex('#3498db');

// Lighten and darken
$lighter = $color->lighten(0.2);      // Lighten by 20% (0.0 to 1.0)
$darker = $color->darken(0.2);        // Darken by 20% (0.0 to 1.0)

// Adjust saturation
$saturated = $color->saturate(0.3);   // Increase saturation by 30%
$desaturated = $color->desaturate(0.3); // Decrease saturation by 30%

// Rotate hue (color wheel)
$rotated = $color->rotate(180);       // Rotate hue by 180 degrees (0-360)

// Set specific lightness
$withLightness = $color->withLightness(0.5); // Set lightness to 50% (0.0 to 1.0)

$color = Color::fromHex('#3498db');

// Brightness (0-255)
$brightness = $color->getBrightness();  // Returns: float (0.0 to 255.0)
$isLight = $color->isLight();           // true if brightness > 128
$isDark = $color->isDark();             // true if brightness <= 128

// Luminance (0.0 to 1.0) - WCAG formula
$luminance = $color->getLuminance();    // Returns: float (0.0 to 1.0)

// Contrast ratio (for accessibility)
$textColor = Color::fromHex('#ffffff');
$ratio = $color->getContrastRatio($textColor); // Returns: float (1.0 to 21.0)

$theme = $palette->getSuggestedSurfaceColors();

use Farzai\ColorPalette\Color;
use Farzai\ColorPalette\ColorPalette;
use Farzai\ColorPalette\PaletteGenerator;
use Farzai\ColorPalette\Theme;
use Farzai\ColorPalette\ThemeGenerator;

// Full 5-role theme from a brand color (via the website-theme strategy):
$palette = (new PaletteGenerator(Color::fromHex('#2196F3')))->websiteTheme();
$theme = Theme::fromPalette($palette);
echo $theme->getPrimaryColor()->toHex();
echo $theme->getSurfaceColor()->toHex();

// Or derive a theme from any extracted palette:
$theme = (new ThemeGenerator)->generate(ColorPalette::fromImage('logo.png', 5));

$textColor = $palette->getSuggestedTextColor($backgroundColor);

// Check for GD
if (extension_loaded('gd')) {
    echo "GD is installed\n";
}

// Check for Imagick
if (extension_loaded('imagick')) {
    echo "Imagick is installed\n";
}

try {
    $extractor = ColorExtractorFactory::gd();
    echo "GD is available\n";
} catch (\RuntimeException $e) {
    echo "GD is not available\n";
}

   $palette = ColorPalette::fromImage('photo.jpg', 5, 'imagick');
   

   $palette = ColorPalette::fromImage('photo.jpg', 10);
   

$color = Color::fromHex('#3498db');

// WRONG - This doesn't work!
$color->lighten(0.2);
echo $color->toHex(); // Still #3498db

// CORRECT - Assign the result
$lighter = $color->lighten(0.2);
echo $lighter->toHex(); // Lighter color!

use Farzai\ColorPalette\ImageLoaderFactory;

$factory = new ImageLoaderFactory;
$loader = $factory->create();

// These will throw SsrfException:
$loader->load('http://localhost/internal-image.jpg');  // Blocked
$loader->load('http://192.168.1.1/image.jpg');         // Blocked
$loader->load('http://[::1]/image.jpg');               // Blocked
$loader->load('file:///etc/passwd');                    // Blocked

// Only public HTTP/HTTPS URLs are allowed:
$loader->load('https://example.com/public-image.jpg'); // OK

> // Guzzle: disable redirect-following so the loader re-validates each hop
> $client = new \GuzzleHttp\Client(['allow_redirects' => false]);
> $loader = (new \Farzai\ColorPalette\ImageLoaderFactory(httpClient: $client))->create();
> 

use Farzai\ColorPalette\Config\HttpClientConfig;
use Farzai\ColorPalette\ImageLoaderFactory;

// Custom file size limit (5MB)
$config = new HttpClientConfig(
    maxFileSizeBytes: 5 * 1024 * 1024
);

$factory = new ImageLoaderFactory(httpConfig: $config);
$loader = $factory->create();

// Will throw HttpException if file exceeds 5MB
$loader->load('https://example.com/huge-image.jpg');

use Farzai\ColorPalette\Config\HttpClientConfig;
use Farzai\ColorPalette\ImageLoaderFactory;

$config = new HttpClientConfig(
    timeoutSeconds: 30,           // Request timeout (default: 30)
    maxRedirects: 0,              // Follow redirects (default: 0 - disabled)
    maxFileSizeBytes: 10485760,   // Max file size in bytes (default: 10MB)
    userAgent: 'MyApp/1.0',       // Custom User-Agent header
    verifySsl: true               // SSL certificate verification (default: true)
);

$factory = new ImageLoaderFactory(httpConfig: $config);
$loader = $factory->create();

use Farzai\ColorPalette\Exceptions\SsrfException;
use Farzai\ColorPalette\Exceptions\HttpException;
use Farzai\ColorPalette\Exceptions\InvalidImageException;

try {
    $loader->load($userProvidedUrl);
} catch (SsrfException $e) {
    // URL validation failed (private IP, invalid protocol, etc.)
    log_security_event('SSRF attempt blocked', $userProvidedUrl);
} catch (HttpException $e) {
    // HTTP error (status code, file size, MIME type, etc.)
    log_error('Failed to download image', $e->getMessage());
} catch (InvalidImageException $e) {
    // Image processing error
    log_error('Invalid image', $e->getMessage());
}

use Farzai\ColorPalette\ColorExtractorFactory;
use Farzai\ColorPalette\ImageLoaderFactory;

// ✓ GOOD: load through the SSRF-protected loader and handle errors.
// (ColorPalette::fromImage() is for local paths only — it does not fetch URLs.)
try {
    $image = (new ImageLoaderFactory)->create()->load($userUrl);
    $palette = (new ColorExtractorFactory)->make('gd')->extract($image, 5);
} catch (SsrfException $e) {
    // Don't expose internal network structure in error messages
    throw new UserFacingException('Invalid URL provided');
}

// ⚠️ The loader already validates the URL against the SSRF rules, but for
// untrusted input add an allowlist for defense in depth (see below).
$image = (new ImageLoaderFactory)->create()->load($_GET['url']);

// ✓ GOOD: Add URL whitelist for extra security
$allowedDomains = ['cdn.example.com', 'images.example.com'];
$host = parse_url($userUrl, PHP_URL_HOST);

if (!in_array($host, $allowedDomains)) {
    throw new Exception('URL not from allowed domain');
}
bash
# Install GD
sudo apt-get install php-gd

# Install Imagick
sudo apt-get install php-imagick
ini
   memory_limit = 256M