Skip to content

Instantly share code, notes, and snippets.

@aklump
Last active January 19, 2018 23:30
Show Gist options
  • Save aklump/526da87550de42fbdea9 to your computer and use it in GitHub Desktop.
Save aklump/526da87550de42fbdea9 to your computer and use it in GitHub Desktop.
Drupal 7 snippet to determine if an image is mostly dark.
<?php
/**
* Determine if an image is mostly dark.
*
* @param string $uri The uri of the image file.
* @param array $options
* - resolution int The larger the number the more measurements will be taken
* and the longer it will take. Defaults to 10.
* - threshold int The luminance threshold. 170 is equal to #acacac.
* @param array $info Pass an array to be filled with data used to calculate
* the answer. The returned keys are:
* - r
* - g
* - b
* - total_luminance
* - average_luminance
*
* @return bool
*
* @see http://stackoverflow.com/questions/5842440/background-image-dark-or-light
*/
function MODULE_NAME_is_dark_image($uri, $options = array(), Array &$info = NULL) {
if (!array_key_exists('gd', image_get_available_toolkits())) {
watchdog('MODULE_NAME', '%func has only been testing with the gd toolkit. Image dark/light detection is not available.', array('%func' => __FUNCTION__), WATCHDOG_ERROR);
return NULL;
}
$images = &drupal_static(__FUNCTION__, array());
if (!array_key_exists($uri, $images)) {
$options += array(
'resolution' => 10,
'threshold' => 170,
);
$image = image_load($uri, 'gd');
$width = $image->info['width'];
$height = $image->info['height'];
$x_step = intval($width / $options['resolution']);
$y_step = intval($height / $options['resolution']);
$info['total_luminance'] = 0;
$sample_no = 1;
for ($x = 0; $x < $width; $x += $x_step) {
for ($y = 0; $y < $height; $y += $y_step) {
$rgb = imagecolorat($image->resource, $x, $y);
$info['r'] = ($rgb >> 16) & 0xFF;
$info['g'] = ($rgb >> 8) & 0xFF;
$info['b'] = $rgb & 0xFF;
// choose a simple luminance formula from here
// http://stackoverflow.com/questions/596216/formula-to-determine-brightness-of-rgb-color
$lum = ($info['r'] + $info['r'] + $info['b'] + $info['g'] + $info['g'] + $info['g']) / 6;
$info['total_luminance'] += $lum;
$sample_no++;
}
}
// work out the average
$info['average_luminance'] = $info['total_luminance'] / $sample_no;
$info['is_dark'] = $info['average_luminance'] < $options['threshold'];
$images[$uri] = $info;
}
return $images[$uri]['is_dark'];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment