Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Added

- `colorKey` pipeline operation to make nodata fill colors transparent. Defaults to a flood from the tile edge and existing alpha so isolated interior matches stay put.

## [2.2.0] - 2026-08-26

### Added
Expand Down Expand Up @@ -169,6 +175,7 @@ Rename `publicBasePath` to `mapAssetBasePath` in Mapbox style configs. The old k

- Initial release of the PHP tile proxy with operation pipeline, caching, and tests.

[Unreleased]: https://github.com/open-mapsight/tile-proxy/compare/v2.2.0...HEAD
[2.2.0]: https://github.com/open-mapsight/tile-proxy/compare/v2.1.2...v2.2.0
[2.1.2]: https://github.com/open-mapsight/tile-proxy/compare/v2.1.1...v2.1.2
[2.1.1]: https://github.com/open-mapsight/tile-proxy/compare/v2.1.0...v2.1.1
Expand Down
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,7 @@ Operations are chained sequentially as defined in the `ops` array. The first ope

* `src`: Fetches the tile from the defined `urls`, or from a `wms` GetMap source. URL templates support `{z}`, `{x}`, `{y}`, `{prefix}`, `{bbox}` / `{bbox3857}` (Web Mercator meters), and `{bbox4326}` (lon,lat,lon,lat).
* `colorFilter`: Applies color filters. Supported filters: `reducedSaturation`, `muted`, `culture`.
* `colorKey`: Makes nodata fill colors transparent (`colors` as `#RRGGBB`, optional `fuzz`, optional `fromEdges`). Defaults to a flood from the tile edge and already-transparent pixels so isolated interior matches stay put. Always encodes PNG.
* `encode`: Re-encodes the current tile to another image type (`mimeType`, optional `quality` for JPEG/WebP).
* `imgOpt`: Optimizes the image using image optimizers.
* `merge`: Merges the current tile with another set of operations.
Expand Down Expand Up @@ -310,6 +311,19 @@ JPEG is the right WMS `FORMAT` for aerial photos (smaller than PNG, widely suppo
]
```

To punch a solid nodata fill out of an aerial before overlaying it, add `colorKey`. `fuzz` is a per-channel tolerance. Keep `fromEdges` at its default (`true`) so interior roofs or shadows that happen to match the fill stay put:

```jsonc
{
"op": "colorKey",
"colors": ["#000000"],
"fuzz": 8,
"cacheServerName": "luftbild-keyed"
}
```

Set `fromEdges` to `false` only when every matching pixel should become transparent, including interior matches.

Leaflet, OpenLayers, and MapLibre can consume the proxied XYZ URL like any other raster tileset.

If the WMS requires Basic auth, set `upstreamHttp.headers.Authorization` in the PHP bootstrap (not in committed JSONC). Some municipal WMS licenses also forbid local storage — disable or shorten `cacheServerTtl` when that applies.
Expand Down
186 changes: 186 additions & 0 deletions classes/Ops/ColorKeyOp.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
<?php

declare(strict_types=1);

namespace OpenMapsight\TileProxy\Ops;

use OpenMapsight\TileProxy\Result;
use OpenMapsight\TileProxy\Utils;
use RuntimeException;

/**
* Make nodata fill colors transparent. Default is a flood from the tile edge
* and from already-transparent pixels, so isolated interior matches (roofs,
* shadows) stay put.
*/
class ColorKeyOp implements OpHandler
{
public function __invoke(callable $next, array $cfg, Result $res): Result
{
if (!$res->isFromCache()) {
Utils::assertImageMimeType($res->mimeType);
$img = Utils::bytesToImage($res->getData());
self::cutImage(
$img,
self::parseColors($cfg['colors'] ?? []),
(int)($cfg['fuzz'] ?? 0),
(bool)($cfg['fromEdges'] ?? true),
);
$res->setData(Utils::imageToBytes('image/png', $img));
}

$res->mimeType = 'image/png';

return $next($res);
}

/**
* @param list<array{0:int,1:int,2:int}> $colors
*/
public static function cutImage($img, array $colors, int $fuzz, bool $fromEdges): void
{
if ($colors === []) {
throw new RuntimeException('colorKey requires `colors`');
}

$width = imagesx($img);
$height = imagesy($img);
imagealphablending($img, false);
imagesavealpha($img, true);
$clear = imagecolorallocatealpha($img, 0, 0, 0, 127);

$isKey = static function (int $r, int $g, int $b) use ($colors, $fuzz): bool {
foreach ($colors as [$cr, $cg, $cb]) {
if (
abs($r - $cr) <= $fuzz
&& abs($g - $cg) <= $fuzz
&& abs($b - $cb) <= $fuzz
) {
return true;
}
}

return false;
};

$rgba = static function (int $pixel): array {
return [
($pixel >> 16) & 0xFF,
($pixel >> 8) & 0xFF,
$pixel & 0xFF,
($pixel >> 24) & 0x7F,
];
};

$match = static function (int $x, int $y) use ($img, $rgba, $isKey): bool {
[$r, $g, $b, $a] = $rgba(imagecolorat($img, $x, $y));

return $a < 127 && $isKey($r, $g, $b);
};

if (!$fromEdges) {
for ($y = 0; $y < $height; $y++) {
for ($x = 0; $x < $width; $x++) {
if ($match($x, $y)) {
imagesetpixel($img, $x, $y, $clear);
}
}
}

return;
}

$visited = array_fill(0, $width * $height, false);
$queue = [];
$enqueue = static function (int $x, int $y) use (&$queue, &$visited, $width, $height): void {
if ($x < 0 || $y < 0 || $x >= $width || $y >= $height) {
return;
}
$i = $y * $width + $x;
if ($visited[$i]) {
return;
}
$visited[$i] = true;
$queue[] = [$x, $y];
};

for ($x = 0; $x < $width; $x++) {
if ($match($x, 0)) {
$enqueue($x, 0);
}
if ($match($x, $height - 1)) {
$enqueue($x, $height - 1);
}
}
for ($y = 0; $y < $height; $y++) {
if ($match(0, $y)) {
$enqueue(0, $y);
}
if ($match($width - 1, $y)) {
$enqueue($width - 1, $y);
}
}

for ($y = 0; $y < $height; $y++) {
for ($x = 0; $x < $width; $x++) {
$a = $rgba(imagecolorat($img, $x, $y))[3];
if ($a < 127) {
continue;
}
$enqueue($x + 1, $y);
$enqueue($x - 1, $y);
$enqueue($x, $y + 1);
$enqueue($x, $y - 1);
}
}

$head = 0;
while ($head < count($queue)) {
[$x, $y] = $queue[$head++];
if (!$match($x, $y)) {
continue;
}
imagesetpixel($img, $x, $y, $clear);
foreach ([[1, 0], [-1, 0], [0, 1], [0, -1]] as [$dx, $dy]) {
$nx = $x + $dx;
$ny = $y + $dy;
if ($nx < 0 || $ny < 0 || $nx >= $width || $ny >= $height) {
continue;
}
$i = $ny * $width + $nx;
if ($visited[$i]) {
continue;
}
if (!$match($nx, $ny)) {
continue;
}
$visited[$i] = true;
$queue[] = [$nx, $ny];
}
}
}

/**
* @param list<mixed> $raw
* @return list<array{0:int,1:int,2:int}>
*/
public static function parseColors(array $raw): array
{
$out = [];
foreach ($raw as $color) {
if (is_string($color) && preg_match('/^#([0-9a-f]{6})$/i', $color, $m) === 1) {
$hex = $m[1];
$out[] = [
hexdec(substr($hex, 0, 2)),
hexdec(substr($hex, 2, 2)),
hexdec(substr($hex, 4, 2)),
];
continue;
}

throw new RuntimeException('colorKey colors must be #RRGGBB');
}

return $out;
}
}
2 changes: 2 additions & 0 deletions classes/Processor.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

use Exception;
use OpenMapsight\TileProxy\Ops\ColorFilterOp;
use OpenMapsight\TileProxy\Ops\ColorKeyOp;
use OpenMapsight\TileProxy\Ops\EncodeOp;
use OpenMapsight\TileProxy\Ops\ImgOptOp;
use OpenMapsight\TileProxy\Ops\MergeOp;
Expand All @@ -21,6 +22,7 @@ protected static function getOpHandlers(): array
{
return [
'colorFilter' => ColorFilterOp::class,
'colorKey' => ColorKeyOp::class,
'encode' => EncodeOp::class,
'imgOpt' => ImgOptOp::class,
'merge' => MergeOp::class,
Expand Down
Loading
Loading