18 декабря 2015, 12:57

Рисуем почтовый индекс на PHP

Возникла тут задча, готовое решение за пять минут гугления не обнаружилось, пришлось сделать.

<?
$index = $_REQUEST['index'];
$d = 40; // ширина цифры

$h = imagecreatetruecolor(345, 105);

$w = imagecolorallocate($h, 255, 255, 255);
$b = imagecolorallocate($h, 0, 0, 0);

imagefill($h, 0, 0, $w);

imagefilledrectangle($h, 0, 0, $d, 10, $b);
imagefilledrectangle($h, 0, 15, $d, 20, $b);

$left = $d + 10;
for ($i = 0; $i < strlen($index); $i++) {
	$char = $index{$i};
	imagefilledrectangle($h, $left, 0, $left + $d, 10, $b);

	imagesetthickness($h, 3);

	switch($char) {
		case 0:
			drawLine($h, $left, 1, 2, $b);
			drawLine($h, $left, 2, 6, $b);
			drawLine($h, $left, 1, 5, $b);
			drawLine($h, $left, 5, 6, $b);
			break;

		case 1:
			drawLine($h, $left, 3, 2, $b);
			drawLine($h, $left, 2, 6, $b);
			break;

		case 2:
			drawLine($h, $left, 1, 2, $b);
			drawLine($h, $left, 2, 4, $b);
			drawLine($h, $left, 5, 4, $b);
			drawLine($h, $left, 5, 6, $b);
			break;

		case 3:
			drawLine($h, $left, 3, 2, $b);
			drawLine($h, $left, 5, 4, $b);
			drawLine($h, $left, 1, 2, $b);
			drawLine($h, $left, 3, 4, $b);
			break;

		case 4:
			drawLine($h, $left, 1, 3, $b);
			drawLine($h, $left, 2, 6, $b);
			drawLine($h, $left, 3, 4, $b);
			break;

		case 5:
			drawLine($h, $left, 1, 2, $b);
			drawLine($h, $left, 1, 3, $b);
			drawLine($h, $left, 3, 4, $b);
			drawLine($h, $left, 4, 6, $b);
			drawLine($h, $left, 5, 6, $b);
			break;

		case 6:
			drawLine($h, $left, 2, 3, $b);
			drawLine($h, $left, 4, 3, $b);
			drawLine($h, $left, 5, 3, $b);
			drawLine($h, $left, 5, 6, $b);
			drawLine($h, $left, 4, 6, $b);
			break;

		case 7:
			drawLine($h, $left, 1, 2, $b);
			drawLine($h, $left, 3, 2, $b);
			drawLine($h, $left, 3, 5, $b);
			break;

		case 8:
			drawLine($h, $left, 1, 2, $b);
			drawLine($h, $left, 2, 6, $b);
			drawLine($h, $left, 1, 5, $b);
			drawLine($h, $left, 5, 6, $b);
			drawLine($h, $left, 3, 4, $b);
			break;

		case 9:
			drawLine($h, $left, 1, 2, $b);
			drawLine($h, $left, 1, 3, $b);
			drawLine($h, $left, 4, 2, $b);
			drawLine($h, $left, 3, 4, $b);
			drawLine($h, $left, 5, 4, $b);
			break;
	}

	$left += $d + 10;
}

/**
 * @param $p1 , $p2 — точки:
 *            1   2
 *            3   4
 *            5   6
 */
function drawLine($h, $l, $p1, $p2, $c) {
	global $d; $p1--; $p2--;
	$points = [[$l, 20], [$l + $d, 20], [$l, 20 + $d], [$l + $d, 20 + $d], [$l, 20 + $d * 2], [$l + $d, 20 + $d * 2]];

	imageline($h, $points[$p1][0], $points[$p1][1], $points[$p2][0], $points[$p2][1], $c);
}

header('Content-Type: image/png');
imagepng($h);