Skip to content

Instantly share code, notes, and snippets.

@kezzico
Created September 12, 2024 17:32
Show Gist options
  • Save kezzico/9fe4820b22ce5761e7c34e8f65356687 to your computer and use it in GitHub Desktop.
Save kezzico/9fe4820b22ce5761e7c34e8f65356687 to your computer and use it in GitHub Desktop.
from PIL import Image
import os
# Define the directory where tiles are stored and the output file
tiles_dir = 'tiles_zoom_16' # Replace with your directory
output_file = 'combined_image_16.png'
# Define the tile size (standard is 256x256 pixels)
tile_size = 256
# Get all tile files and extract their coordinates
tile_files = [f for f in os.listdir(tiles_dir) if f.endswith('.png')]
tile_coords = [tuple(map(int, os.path.splitext(f)[0].split('_'))) for f in tile_files]
if not tile_coords:
raise ValueError("No tile files found in the specified directory.")
# Determine the range of x and y coordinates
x_coords, y_coords = zip(*tile_coords)
min_x, max_x = min(x_coords), max(x_coords)
min_y, max_y = min(y_coords), max(y_coords)
# Calculate the size of the final image based on the range of coordinates
image_width = (max_x - min_x + 1) * tile_size
image_height = (max_y - min_y + 1) * tile_size
# Create a new blank image with the calculated size
combined_image = Image.new('RGBA', (image_width, image_height))
# Paste each tile onto the combined image
for (x, y) in tile_coords:
tile_file = f"{x}_{y}.png"
tile_path = os.path.join(tiles_dir, tile_file)
if os.path.exists(tile_path):
# Load the tile image
tile_image = Image.open(tile_path)
# Compute the position where the tile should be placed
x_pos = (x - min_x) * tile_size
y_pos = (y - min_y) * tile_size
# Paste the tile onto the combined image
combined_image.paste(tile_image, (x_pos, y_pos))
else:
print(f"Tile {tile_file} not found.")
# Save the combined image
combined_image.save(output_file)
print(f'Combined image saved as {output_file}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment