Last active
February 26, 2024 21:36
-
-
Save artlung/80f42ff6f37c71dbf98ab0c5da652e40 to your computer and use it in GitHub Desktop.
Parse Images for Colors and Populate a CSS File. Uses composer library ColorExtractor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "artlung/parse-images-for-color", | |
"autoload": { | |
"psr-4": { | |
"Artlung\\ParseImagesForColor\\": "src/" | |
} | |
}, | |
"authors": [ | |
{ | |
"name": "Joe Crawford", | |
"email": "joe@artlung.com" | |
} | |
], | |
"require": { | |
"league/color-extractor": "^0.4.0" | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require 'vendor/autoload.php'; | |
// https://stackoverflow.com/questions/10290259/detect-main-colors-in-an-image-with-php | |
use League\ColorExtractor\Color; | |
use League\ColorExtractor\ColorExtractor; | |
use League\ColorExtractor\Palette; | |
$directory = '../thumbs-trimmed/shot-scraper'; | |
$files = scandir($directory); | |
$files = array_diff($files, array('..', '.')); | |
$files = array_values($files); | |
$fileName = 'output.css'; | |
foreach ($files as $file) { | |
if (strpos($file, '.png') === false) { | |
continue; | |
} | |
ob_start(); | |
$className = '.' . str_replace('.png', | |
'', str_replace('artlung-com-headers--', | |
'header-', $file)); | |
print 'body' . $className . " {\n"; | |
$im = imagecreatefrompng($directory . '/' . $file); | |
if (!$im) { | |
echo '/* Could not create image resource for ' . $file . " */\n"; | |
continue; | |
} | |
$palette = Palette::fromGD($im); | |
$topColors = $palette->getMostUsedColors(12); | |
$colorCount = count($palette); | |
// an extractor is built from a palette | |
$extractor = new ColorExtractor($palette); | |
// League\ColorExtractor\ColorExtractor library does work to | |
// get the most representative colors | |
$colors = $extractor->extract(5); | |
// populate the css file with colors | |
foreach($colors as $color) { | |
printf("--color: %s;\n", Color::fromIntToHex($color)); | |
printf("--backgroundColor: %s;\n", Color::fromIntToHex($color)); | |
} | |
print "}\n"; | |
$css = ob_get_clean(); | |
file_put_contents($fileName, $css, FILE_APPEND); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment