Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Colorjizz Laravel Package

mischiefcollective/colorjizz

ColorJizz-PHP is a lightweight color library for converting and manipulating colors across formats like RGB, CMYK, Hex, HSV, CIELab/LCh, XYZ, and Yxy. Supports chaining operations (hue, saturation, greyscale) while keeping originals immutable.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install via Composer (recommended):

    composer require mischiefcollective/colorjizz
    

    No manual autoloading needed—Laravel’s Composer autoloader handles it.

  2. First Use Case: Convert a Hex Color to RGB

    use MischiefCollective\ColorJizz\Formats\Hex;
    
    $hexColor = Hex::fromString('#FF5733');
    $rgb = $hexColor->toRGB();
    // Returns: RGB(255, 87, 51)
    
  3. Quick Harmony Check

    $complementary = $hexColor->complementary();
    // Returns: Hex(0x00A8CC)
    

Where to Look First

  • Format Classes: app/ColorJizz/Formats/ (e.g., Hex.php, RGB.php).
  • Manipulation Methods: Chainable methods like hue(), saturation(), brightness().
  • Harmony Generators: complementary(), analogous(), triadic().

Implementation Patterns

1. Color Conversion Workflows

Pattern: Convert between formats dynamically (e.g., for UI themes or image processing).

// Convert user-uploaded hex to CMYK for print
$hex = Hex::fromString(request('color'));
$cmyk = $hex->toCMYK();
$printSafeColor = $cmyk->adjustK(10); // Darken for print

Tip: Cache converted colors if reused (e.g., in a theme system):

$cachedRgb = Cache::remember("color_{$hex}", 3600, fn() => $hex->toRGB());

2. Theme Generation

Pattern: Generate a palette from a base color.

$base = Hex::fromString('#3498db');
$theme = [
    'primary' => $base,
    'secondary' => $base->lightness(20),
    'accent' => $base->complementary()->saturation(80),
];

Integration with Laravel:

// Store in config
config(['theme.colors' => $theme]);

// Blade template
<div style="background: {{ config('theme.colors.primary') }}"></div>

3. Image Processing

Pattern: Adjust colors in interventions or GD libraries.

use Intervention\Image\Facades\Image;

$image = Image::make('photo.jpg');
$hex = Hex::fromString('#FF0000');
$tinted = $image->tint($hex->toRGB()->toArray());

4. Accessibility Checks

Pattern: Ensure color contrast meets WCAG standards.

$textColor = Hex::fromString('#333333');
$bgColor = Hex::fromString('#ffffff');
$contrastRatio = $textColor->contrastRatio($bgColor);

if ($contrastRatio < 4.5) {
    // Fallback to high-contrast colors
}

5. Dynamic UI Feedback

Pattern: Use color harmonies for notifications.

$statusColor = match ($status) {
    'success' => Hex::fromString('#2ecc71')->lightness(10),
    'error' => Hex::fromString('#e74c3c')->darkness(10),
    default => Hex::fromString('#f39c12'),
};

Gotchas and Tips

Pitfalls

  1. Immutable Objects:

    • Methods like hue() return new instances. Avoid:
      $color->hue(30)->hue(20); // Only applies 20° (last call wins)
      
    • Fix: Chain or reassign:
      $adjusted = $color->hue(30)->hue(20);
      
  2. Floating-Point Precision:

    • HSV/HSL values may have rounding errors. Use round() for consistency:
      $hsv = $hex->toHSV();
      $safeHue = round($hsv->h, 2);
      
  3. Unsupported Formats:

    • CIELab/CIELCh require valid ranges (e.g., L must be 0–100). Validate inputs:
      $lab = new CIELab(max(0, min(100, $l)), $a, $b);
      
  4. String Parsing Quirks:

    • Hex::fromString() accepts #RRGGBB, RRGGBB, or named colors ('red'). Handle edge cases:
      $hex = Hex::fromString(str_replace('#', '', $input) ?? '');
      

Debugging Tips

  1. Inspect Intermediate Values:

    $rgb = Hex::fromString('#FF5733');
    dd($rgb->toHSV(), $rgb->toCIELab());
    
  2. Check for Deprecated Methods:

    • The package is unmaintained. Test edge cases (e.g., Yxy format) in isolation.
  3. Fallback for Missing Features:

    • Extend classes for missing harmonies (e.g., "split-complementary"):
      class ExtendedHex extends Hex {
          public function splitComplementary() {
              $complement = $this->complementary();
              return $this->analogous(15)->mix($complement, 0.5);
          }
      }
      

Extension Points

  1. Custom Color Spaces:

    • Implement MischiefCollective\ColorJizz\Interfaces\ColorInterface for new formats.
  2. Laravel Helpers:

    • Create a facade for common operations:
      // app/ColorJizz.php
      namespace App\ColorJizz;
      use MischiefCollective\ColorJizz\Formats\Hex;
      
      class ColorJizz {
          public static function theme($baseHex) {
              return collect(['primary', 'secondary', 'accent'])
                  ->map(fn($type) => match($type) {
                      'primary' => $baseHex,
                      'secondary' => $baseHex->lightness(20),
                      'accent' => $baseHex->complementary(),
                  });
          }
      }
      
  3. Validation Rules:

    • Add to Laravel’s validator:
      Validator::extend('valid-color', function ($attribute, $value, $parameters) {
          try {
              Hex::fromString($value);
              return true;
          } catch (\Exception $e) {
              return false;
          }
      });
      

Performance Notes

  • Avoid Repeated Conversions: Store converted colors in a service or cache.
  • Batch Processing: For bulk operations (e.g., generating palettes), use Laravel’s collect():
    $colors = collect(['#FF0000', '#00FF00', '#0000FF'])
        ->map(fn($hex) => Hex::fromString($hex)->toRGB());
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky