public function whenMediaHasBeenAdded(MediaHasBeenAdded $event) { $media = $event->media; $dominantColor = ColorThief::getColor($media->getPath()); $hexColor = (new Rgb(...$dominantColor))->toHex(); $media->setCustomProperty('dominantColor', $hexColor); $media->save(); }
/** * Gets color palette for image * * @param AssetFileModel|string $image * @param $colorCount * @param $quality * @param $colorValue * @return array * @throws Exception */ public function getColorPalette($image, $colorCount, $quality, $colorValue) { $pathsModel = new Imager_ImagePathsModel($image); if (!IOHelper::getRealPath($pathsModel->sourcePath)) { throw new Exception(Craft::t('Source folder “{sourcePath}” does not exist', array('sourcePath' => $pathsModel->sourcePath))); } if (!IOHelper::fileExists($pathsModel->sourcePath . $pathsModel->sourceFilename)) { throw new Exception(Craft::t('Requested image “{fileName}” does not exist in path “{sourcePath}”', array('fileName' => $pathsModel->sourceFilename, 'sourcePath' => $pathsModel->sourcePath))); } $palette = ColorThief::getPalette($pathsModel->sourcePath . $pathsModel->sourceFilename, $colorCount, $quality); return $colorValue == 'hex' ? $this->_paletteToHex($palette) : $palette; }
public function setColors() { AWS::createClient('s3')->getObject(array('Bucket' => Credential::AWSS3BucketLargeThumbs, 'Key' => $this->bannerImage->filename, 'SaveAs' => public_path() . '/media/temp/' . $this->bannerImage->filename)); // Fetch an RGB array of the dominant color $rgb = ColorThief::getColor(public_path() . '/media/temp/' . $this->bannerImage->filename); // Unlink the file, it is no longer needed. unlink(public_path() . '/media/temp/' . $this->bannerImage->filename); // Convert RGB array to hex $hex = '#' . dechex($rgb[0]) . dechex($rgb[1]) . dechex($rgb[2]); // Set properties $this->attributes['dark_color'] = $hex; $this->attributes['light_color'] = '#' . (new Color($hex))->lighten(); }
function avgimgcolorhook($file) { if (!$file->isImage()) { return; } try { if ($file->avgcolor() == "") { require_once kirby()->roots()->index() . '/vendor/autoload.php'; $color = \ColorThief\ColorThief::getColor($file->root(), 100); $file->update(['avgcolor' => rgb2hex($color)]); } } catch (Exception $e) { return response::error($e->getMessage()); } }
private static function quantize($pixels, $maxcolors) { // short-circuit if (!count($pixels) || $maxcolors < 2 || $maxcolors > 256) { // echo 'wrong number of maxcolors'."\n"; return false; } $histo = static::getHisto($pixels); // check that we aren't below maxcolors already //if (count($histo) <= $maxcolors) { // XXX: generate the new colors from the histo and return //} $vbox = static::vboxFromPixels($pixels, $histo); $pq = new PQueue(function ($a, $b) { return ColorThief::naturalOrder($a->count(), $b->count()); }); $pq->push($vbox); // first set of colors, sorted by population static::quantizeIter($pq, self::FRACT_BY_POPULATIONS * $maxcolors, $histo); // Re-sort by the product of pixel occupancy times the size in color space. $pq2 = new PQueue(function ($a, $b) { return ColorThief::naturalOrder($a->count() * $a->volume(), $b->count() * $b->volume()); }); for ($i = $pq->size(); $i > 0; $i--) { $pq2->push($pq->pop()); } // next set - generate the median cuts using the (npix * vol) sorting. static::quantizeIter($pq2, $maxcolors - $pq2->size(), $histo); // calculate the actual colors $cmap = new CMap(); for ($i = $pq2->size(); $i > 0; $i--) { $cmap->push($pq2->pop()); } return $cmap; }
private function getImageColorInfo($filename) { $filenameSample = $filename . '.sample.jpg'; if (file_exists($filename)) { if (!file_exists($filenameSample)) { $imageFile = Image::fromFile($filename); $imageFile->resize(200, 200, Image::FILL); $imageFile->save($filenameSample, 100, Image::JPEG); } $client = new Client(); $image = $client->loadJpeg($filenameSample); $palette = $image->extract(6); $dominantColor = ColorThief::getColor($filenameSample); $dominantColor = \Aprila\Utils\Colors::rgbToHex($dominantColor); $color = new Color($dominantColor); $isDark = $color->isDark(); $imageColorInfo = ['main' => $dominantColor, 'palette' => $palette, 'isDark' => $isDark]; FileSystem::delete($filenameSample); return $imageColorInfo; } return []; }
/** * @dataProvider provideNaturalOrderComparison */ public function testNaturalOrder($left, $right, $expected) { $this->assertSame($expected, ColorThief::naturalOrder($left, $right)); }
public function actionUpload() { $file = UploadedFile::getInstanceByName('file'); if ($file) { $destName = time() . '_' . $file->name; $targetFile = \Yii::getAlias('@webroot') . DIRECTORY_SEPARATOR . '_lib' . DIRECTORY_SEPARATOR . $destName; $file->saveAs($targetFile); $filePath = \Yii::getAlias('@app/workspace/elements') . DIRECTORY_SEPARATOR . 'asset' . '.json'; $elementDefinition = Json::decode(file_get_contents($filePath), false); // Add core fields. $elementDefinition->fields[] = Json::decode('{ "label": "UUID", "key": "uuid", "type": "textInput", "visibleInGrid": true, "rules": [["string", {"max": 128}]], "options": {"disabled":true}}', false); $elementDefinition->fields[] = Json::decode('{ "label": "Path", "key": "path", "type": "textInput", "visibleInGrid": true, "rules": [["string", {"max": 128}]]}', false); $elementDefinition->fields[] = Json::decode('{ "label": "Slug", "key": "slug", "type": "textInput", "visibleInGrid": true, "rules": [["string", {"max": 128}]]}', false); $elementDefinition->fields[] = Json::decode('{ "label": "State", "key": "state", "type": "dropDownList", "visibleInGrid": true, "rules": [["required"], ["string", {"max": 128}]], "options": {"prompt":"Please set state"}, "items": {"0":"Offline", "1":"Draft", "2":"Online", "3":"Archived"}}', false); $fields = []; foreach ($elementDefinition->fields as $field) { array_push($fields, $field->key); } $model = new CrelishDynamicJsonModel($fields); $model->identifier = 'asset'; $model->systitle = $destName; $model->title = $destName; $model->src = \Yii::getAlias('@web') . '/' . '_lib' . '/' . $destName; $model->mime = $file->type; $model->size = $file->size; $model->state = 2; $model->save(); try { $domColor = ColorThief::getColor($targetFile, 20); $palColor = ColorThief::getPalette(\Yii::getAlias('@webroot') . DIRECTORY_SEPARATOR . '_lib' . DIRECTORY_SEPARATOR . $destName); $model->colormain_rgb = Json::encode($domColor); $model->colormain_hex = '#' . sprintf('%02x', $domColor[0]) . sprintf('%02x', $domColor[1]) . sprintf('%02x', $domColor[2]); $model->save(); $model->colorpalette = Json::encode($palColor); $model->save(); } catch (Exception $e) { \Yii::$app->session->setFlash('secondary', 'Color theft could not be completed. (Image too large?)'); } } return false; }
function getColor($path) { return ColorThief::getColor($path); }
/** * The actual processing TASK * * Should return an array with database properties for sys_file_metadata to write * * @param File $file * @param array $previousExtractedData optional, contains the array of already extracted data * @return array */ public function extractMetaData(File $file, array $previousExtractedData = []) { $metadata = []; try { if (!class_exists('ColorThief\\ColorThief')) { throw new \RuntimeException('Class ColorThief\\ColorThief does not exist', 1470749087524); } $path = $file->getForLocalProcessing(); $averageColor = ColorThief::getColor($path); if (!is_array($averageColor)) { throw new \RuntimeException('$averageColor is not an array', 1470749109020); } if (count($averageColor) !== 3) { throw new \RuntimeException('$averageColor is an array, but has less than 3 items', 1470749136303); } $r = dechex((int) $averageColor[0]); $g = dechex((int) $averageColor[1]); $b = dechex((int) $averageColor[2]); $metadata['average_color'] = '#' . $r . $g . $b; $this->logger->debug(sprintf('Extracted average color "%s"', $metadata['average_color']), ['file' => $file->getUid()]); } catch (\Exception $e) { $this->logger->error($e->getCode() . ': ' . $e->getMessage(), ['file' => $file->getUid()]); } return $metadata; }
public function determineDominantColor() { $this->log('Auto-determine dominant color', 2); $color = ColorThief::getColor($this->gd); $color = '#' . str_pad(dechex($color[0]), 2, '0', STR_PAD_LEFT) . str_pad(dechex($color[1]), 2, '0', STR_PAD_LEFT) . str_pad(dechex($color[2]), 2, '0', STR_PAD_LEFT); $this->log('Success: ' . $color, 2); return $color; }
/** * @param LimitHexQualityInterface $limitHexQualityData * * @return array */ protected function searchForImagesByHash(LimitHexQualityInterface $limitHexQualityData) { $rgb = $this->hex2rgb($limitHexQualityData->getHex()); $images = array(); $getLimit = $limitHexQualityData->getLimit() * 3; $fetchAll = function ($getLimit, &$fetchedImages = null) use(&$fetchAll) { if (is_null($fetchedImages)) { $images = $this->fetch($getLimit); } else { $images = $this->instagramWrapper->pagination($fetchedImages, $getLimit); } if (!is_null($images) || !empty($images) && !empty($images->meta) && $images->meta->code == '200') { if (is_null($fetchedImages)) { $fetchedImages = $images; } else { $fetchedImages->pagination = $images->pagination; $fetchedImages->data = array_merge($fetchedImages->data, $images->data); } } else { return $fetchedImages; } if (count($fetchedImages->data) < $getLimit && !empty($images->pagination)) { return $fetchAll($getLimit, $fetchedImages); } return $fetchedImages; }; $quality = $limitHexQualityData->getQuality(); $count = 0; $rec = function ($limit, $rgb, $fetchedImages) use(&$rec, &$images, $quality, &$count, $fetchAll, $getLimit) { if (is_object($fetchedImages) && !empty($fetchedImages->data) && is_array($fetchedImages->data)) { $sorted = []; foreach ($fetchedImages->data as $item) { $count++; $diff = $this->colorDiff($rgb, ColorThief::getColor($item->images->thumbnail->url, 1)); if ($item->type != 'image' || $diff >= 300 + ceil($count / 10) * 100) { continue; } $sorted[] = ['i' => $item->images->{$quality}, 'diff' => $diff]; } usort($sorted, function ($a, $b) { if ($a['diff'] == $b['diff']) { return 0; } return $a['diff'] < $b['diff'] ? -1 : 1; }); foreach ($sorted as $item) { if (count($images) >= $limit) { return null; } $images[] = $item; } $count = 0; unset($fetchedImages->data); return $rec($limit, $rgb, $fetchAll($getLimit, $fetchedImages)); } return null; }; $rec($limitHexQualityData->getLimit(), $rgb, $fetchAll($getLimit)); usort($images, function ($a, $b) { if ($a['diff'] == $b['diff']) { return 0; } return $a['diff'] < $b['diff'] ? -1 : 1; }); return array_map(function ($item) { return $item['i']; }, $images); }
/** * Get the dominant colors of this Image * @param Int $colorCount Count of colors to return * @return Array */ public function dominantColorPalette($colorCount = 5) { $c = ColorThief::getPalette($sourceImage = $this->owner->getFullPath(), $colorCount = $colorCount, $quality = Config::inst()->get(get_called_class(), 'quality')); return array_map(array(get_called_class(), 'array_to_hex'), $c); }
#!/usr/bin/env php <?php require_once __DIR__ . '/vendor/autoload.php'; function rgb2hex($r, $g = null, $b = null) { if (is_array($r) && count($r) == 3) { list($r, $g, $b) = $r; } $r = intval($r); $g = intval($g); $b = intval($b); $r = dechex($r < 0 ? 0 : ($r > 255 ? 255 : $r)); $g = dechex($g < 0 ? 0 : ($g > 255 ? 255 : $g)); $b = dechex($b < 0 ? 0 : ($b > 255 ? 255 : $b)); return '#' . (strlen($r) < 2 ? '0' : '') . $r . (strlen($g) < 2 ? '0' : '') . $g . (strlen($b) < 2 ? '0' : '') . $b; } foreach (glob(__DIR__ . '/content/posts/2*') as $postDir) { foreach (glob($postDir . '/*.jpg') as $img) { $metaFile = $img . '.txt'; $meta = file_exists($metaFile) ? file_get_contents($metaFile) : ''; if (strpos($meta, 'Avgcolor') !== false) { continue; } $avgColor = \ColorThief\ColorThief::getColor($img, 100); file_put_contents($metaFile, ($meta ? $meta . "\n\n----\n\n" : '') . "Avgcolor: " . rgb2hex($avgColor)); echo $img . ' => ' . rgb2hex($avgColor) . "\n"; } }