JulienBreux
6/19/2013 - 12:56 PM

Croping for OpenLayers|OpenStreetMap

Croping for OpenLayers|OpenStreetMap

#!/usr/bin/php
<?php
$widthTile = 256;
$heightTile = 256;

if (!isset($argv[1]))
{
  exit('No input file argument'.PHP_EOL);
}

if (!file_exists($argv[1]))
{
  exit('No input file'.PHP_EOL);
}

$file = $argv[1];

if (!preg_match('#([0-9]+)-([0-9]+)-([0-9]+)\.png#', $file))
{
  exit('Bad input file name (use Z-Y-X.png)'.PHP_EOL);
}

list($filename, $extension) = explode('.', $file);
list($z, $x, $y) = explode('-', $filename);

$dir = "tiles/$z";

if (!is_dir($dir))
{
  mkdir($dir);
}

// Crop image
echo "[".date('Y-m-d H:i:s')."] Image croping strat".PHP_EOL;

exec("convert -crop {$widthTile}x{$heightTile} +repage +adjoin {$file} {$dir}/%d.png");

echo "[".date('Y-m-d H:i:s')."] Image croping end".PHP_EOL;

// Create tree
list($widthImage, $heightImage, $typeImage, $attrImage) = getimagesize($file);

$numberX = $widthImage / $widthTile;
$numberY = $heightImage / $heightTile;

// Read X directories
for ($i = $x; $i < ($x + $numberX); $i++)
{
        // X Directory
        mkdir($dir.'/'.$i);
        echo "Created: $dir/$i".PHP_EOL;
}

$numberFiles = $numberX * $numberY;

$firstFile = $currentFile = $y;
$lastFile = $y + $numberY;

$firstDirectory = $currentDirectory = $x;
$lastDirectory = $x + $numberX - 1;

for ($i = 0; $i < $numberFiles; $i++)
{
        $source = $dir.'/'.$i.'.png';
        $destination = $dir.'/'.$currentDirectory.'/'.$currentFile.'.png';

        copy($source, $destination);
        unlink($source);

        echo "Copy '$source' to '$destination'".PHP_EOL;

        $currentDirectory++;
        if ($currentDirectory > $lastDirectory)
        {
                $currentDirectory = $firstDirectory;
                $currentFile++;
        }
}