Skip to content

Instantly share code, notes, and snippets.

@thekid
Last active November 4, 2022 16:39
Show Gist options
  • Save thekid/795c35bec603c0f217cb5445cc901ded to your computer and use it in GitHub Desktop.
Save thekid/795c35bec603c0f217cb5445cc901ded to your computer and use it in GitHub Desktop.
<?php
use de\thekid\dialog\color\Colors;
use img\Image;
use img\io\StreamReader;
use io\{File, Path, Folder};
use util\cmd\Console;
use util\profiling\Timer;
class Glob implements IteratorAggregate {
public function __construct(private Path $base, private string $pattern) { }
public function getIterator(): Traversable {
foreach (glob($this->base.$this->pattern, GLOB_NOSORT | GLOB_BRACE) as $file) {
yield new Path($file);
}
}
}
$out= (new File('out.html'))->out();
$out->write('<!DOCTYPE html><html lang="en"><head>');
$out->write('<style type="text/css">body { margin: 0; padding: 0; } * { box-sizing: border-box; }</style>');
$out->write('</head><body>');
$out->write('<div style="width: 100%; padding: 1rem">');
$colors= new Colors(10);
$out->write('<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem">');
$t= (new Timer())->start();
foreach (array_slice($argv, 1) as $input) {
$p= new Path($input);
foreach ($p->isFile() ? [$p] : new Glob($p, 'thumb*.webp') as $entry) {
Console::writeLine($entry);
$palette= $colors->palette(Image::loadFrom(new StreamReader($entry->asFile())), 5);
$boxes= '';
foreach ($palette as $color) {
$boxes.= '<div style="background: '.$color->toHex().'; width: 2.5rem; height: 2.5rem"></div>';
}
$ambient= "{$palette[0]->red} {$palette[0]->green} {$palette[0]->blue}";
$out->write('<div>
<div>
<img alt="Fixture" width="100%" style="aspect-ratio: 16 / 10; object-fit: cover; border: .5rem solid rgb('.$ambient.' / .4)" src="'.$entry->toString('/').'">
</div>
<div style="display: flex; gap: 1rem; margin-top: .5rem">
'.$boxes.'
</div>
</div>');
}
}
$t->stop();
$out->write('</div>');
$out->write('</div></body>');
$out->close();
Console::writeLinef('Quality %d -> %.3f seconds', $colors->quality, $t->elapsedTime());
@thekid
Copy link
Author

thekid commented Nov 4, 2022

Compare to https://lokeshdhakar.com/projects/color-thief/#examples:

$ xp colors.script.php color-thief/*.jpg
color-thief\image-1.e59bc3bd.jpg
color-thief\image-2.4461c1c0.jpg
color-thief\image-3.919e184e.jpg
Quality 10 -> 0.208 seconds

Colorthief.js example images with XP

The first color is what Colorthief.js regards as the dominant color.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment