<style>
	table.img {
		border-collapse: collapse;
		border-spacing: 0;
		table-layout: fixed;
	}
	table.img td {
		padding: 0;
		height: 1px;
	}
	:not(figure) > table.img,
	figure:has(> table.img) {
		margin-top: 1.5em;
		margin-bottom: 1.5em;
	}
</style>

<?php
	function PrintImageTable($image, $colorTransparent = '', $colorSearch = '', $colorReplace = '')
	{
		if (substr($image, -1) === '=')
			$img = imagecreatefromstring(base64_decode($image));
		else if (file_exists($image))
			$img = imagecreatefromstring(file_get_contents($image));
		else return;
		$width = imagesx($img);
		$height = imagesy($img);
		echo "<table class=\"nostyle img\" style=\"width:{$width}px;\">";
		for($y = 0; $y < $height; $y++)
		{
			echo '<tr>';
			$colorPrev = '';
			$colspan = 0;
			for($x = 0; $x < $width; $x++)
			{
				$color = sprintf("#%06X", imagecolorat($img, $x, $y));
				if ($colorPrev === '' || $color === $colorPrev)
					$colspan++;
				else
				{
					PrintImageTableData($colspan, $colorPrev, $colorTransparent, $colorSearch, $colorReplace);
					$colspan = 1;
				}
				$colorPrev = $color;
			}
			PrintImageTableData($colspan, $colorPrev, $colorTransparent, $colorSearch, $colorReplace);
			echo '</tr>';
		}
		echo '</table>';
	}

	function PrintImageTableData($colspan, $color, $colorTransparent, $colorSearch, $colorReplace)
	{
		$cssBackgroundColor = "background-color:$color;";
		if ($color === $colorTransparent)
			$cssBackgroundColor = '';
		if ($color === $colorSearch)
			$cssBackgroundColor = "background-color:$colorReplace;";

		if ($colspan > 1)
			echo "<td colspan=\"$colspan\" style=\"{$cssBackgroundColor}\"></td>";
		else
			echo "<td style=\"{$cssBackgroundColor}\"></td>";
	}
?>