1<?php
2
3namespace Mpdf\Gif;
4
5/**
6 * GIF Util - (C) 2003 Yamasoft (S/C)
7 *
8 * All Rights Reserved
9 *
10 * This file can be freely copied, distributed, modified, updated by anyone under the only
11 * condition to leave the original address (Yamasoft, http://www.yamasoft.com) and this header.
12 *
13 * @link http://www.yamasoft.com
14 */
15class ColorTable
16{
17
18	var $m_nColors;
19
20	var $m_arColors;
21
22	public function __construct()
23	{
24		unset($this->m_nColors);
25		unset($this->m_arColors);
26	}
27
28	function load($lpData, $num)
29	{
30		$this->m_nColors = 0;
31		$this->m_arColors = [];
32
33		for ($i = 0; $i < $num; $i++) {
34			$rgb = substr($lpData, $i * 3, 3);
35			if (strlen($rgb) < 3) {
36				return false;
37			}
38
39			$this->m_arColors[] = (ord($rgb[2]) << 16) + (ord($rgb[1]) << 8) + ord($rgb[0]);
40			$this->m_nColors++;
41		}
42
43		return true;
44	}
45
46	function toString()
47	{
48		$ret = "";
49
50		for ($i = 0; $i < $this->m_nColors; $i++) {
51			$ret .=
52				chr(($this->m_arColors[$i] & 0x000000FF)) . // R
53				chr(($this->m_arColors[$i] & 0x0000FF00) >> 8) . // G
54				chr(($this->m_arColors[$i] & 0x00FF0000) >> 16);  // B
55		}
56
57		return $ret;
58	}
59
60	function colorIndex($rgb)
61	{
62		$rgb = intval($rgb) & 0xFFFFFF;
63		$r1 = ($rgb & 0x0000FF);
64		$g1 = ($rgb & 0x00FF00) >> 8;
65		$b1 = ($rgb & 0xFF0000) >> 16;
66		$idx = -1;
67
68		for ($i = 0; $i < $this->m_nColors; $i++) {
69			$r2 = ($this->m_arColors[$i] & 0x000000FF);
70			$g2 = ($this->m_arColors[$i] & 0x0000FF00) >> 8;
71			$b2 = ($this->m_arColors[$i] & 0x00FF0000) >> 16;
72			$d = abs($r2 - $r1) + abs($g2 - $g1) + abs($b2 - $b1);
73
74			if (($idx == -1) || ($d < $dif)) {
75				$idx = $i;
76				$dif = $d;
77			}
78		}
79
80		return $idx;
81	}
82}
83