data2image/CharColorConverter.class.php

74 lines
1.7 KiB
PHP

<?php
/**
* This class contains some library-functions for converting a string to a color [depending on certain modes].
* @author JPT
*/
class CharColorConverter {
/**
* @var array
*/
protected $colortable;
/**
* Default constructor.
* @return void
*/
public function __construct() {
$this->buildColorTable();
}
/**
* Returns an array with RGB for the corresponding index.
* @param int $index Index from 0 to 1530. (Everything above will result the same)
* @return array
* TODO: Function to reverse this one.
* NOTICE: I will use 0 - 1275 for human readability;
*/
protected function index2rgb($index = 0) {
$r = 255;
$g = 0;
$b = 0;
//the elseif fixes a glitch.
for($i = 0; $i < $index; $i++) {
if($r < 255 && $g === 0 && $b === 255) $r++;
elseif($r === 255 && $g < 255 && $b === 0) $g++;
elseif($r === 0 && $g === 255 && $b < 255) $b++;
elseif($r > 0 && $g === 255 && $b === 0) $r--;
elseif($r === 0 && $g > 0 && $b === 255) $g--;
elseif($r === 255 && $g === 0 && $b > 0) $b--;
//DEBUG
//$k = $i + 1;
//echo "I:$k\t$r,$g,$b\r\n";
}
return array($r, $g, $b);
}
/**
* Creates the colortable.
* @return void
*/
protected function buildColorTable() {
$this->colortable = array();
for($i = 0; $i <= 1275; $i++) {
$this->colortable[$i] = $this->index2rgb($i);
}
}
/**
* Converts a single char to a string.
* @param string $string
* @return array RGB
*/
public function charToColor($string) {
if(strlen($string) === 0) throw new Exception("Empty string given!");
$index = ord($string) * 5;
$color = $this->colortable[$index];
return $color;
}
}
?>