You are here

function _spaces_design_image_autocolor in Spaces 6.2

Attempt to retrieve a suitable background color value from an image.

1 call to _spaces_design_image_autocolor()
spaces_design_upload_validate in spaces_design/spaces_design.spaces.inc
Element validator for logo upload. Actually handles file creation and value setting tasks all at once.

File

spaces_design/spaces_design.module, line 160

Code

function _spaces_design_image_autocolor($filepath) {

  // Do additional handling post-save
  $image = imageapi_image_open($filepath);
  $toolkit = variable_get('imageapi_image_toolkit', 'imageapi_gd');

  // Currently we only handle background color selection through the GD library.
  $autocolor = '';
  if ($toolkit == 'imageapi_gd' && !empty($image->resource)) {
    $raw = array();
    $raw['nw'] = imagecolorat($image->resource, 0, 0);
    $raw['ne'] = imagecolorat($image->resource, $image->info['width'] - 1, 0);
    $raw['se'] = imagecolorat($image->resource, $image->info['width'] - 1, $image->info['height'] - 1);
    $raw['sw'] = imagecolorat($image->resource, 0, $image->info['height'] - 1);
    $colors = array();
    foreach ($raw as $k => $index) {
      $rgb = imagecolorsforindex($image->resource, $index);
      $color = array();
      $color[] = str_pad(dechex($rgb['red']), 2, '0', STR_PAD_LEFT);
      $color[] = str_pad(dechex($rgb['green']), 2, '0', STR_PAD_LEFT);
      $color[] = str_pad(dechex($rgb['blue']), 2, '0', STR_PAD_LEFT);
      $color = "#" . implode('', $color);
      $colors[$color] = $colors[$color] + 1;
    }
    $max = 1;
    $excluded = array(
      '#ffffff',
      '#000000',
    );
    foreach ($colors as $color => $count) {
      $unpacked = _color_unpack($color, TRUE);
      $hsl = _color_rgb2hsl($unpacked);
      if ($count > $max && !in_array($color, $excluded) && $hsl[2] < 0.95 && $hsl[2] > 0.05) {
        $autocolor = $color;
      }
    }
  }
  return $autocolor;
}