geocalc-mcp / route_utils.py
Renzo
Update image rendering in route_utils to use WEBP format and optimize quality
b1a5d57
raw
history blame
2.31 kB
import os
import uuid
import tempfile
import staticmaps
from PIL import Image
TEMP_DIR = tempfile.mkdtemp(prefix="geocalc_")
def generate_route_image_file(coords, start_lat, start_lon, end_lat, end_lon):
"""Generate route image and save to temp file."""
context = staticmaps.Context()
context.set_tile_provider(staticmaps.tile_provider_OSM)
# Create route line
line = staticmaps.Line(
[staticmaps.create_latlng(lat, lng) for lat, lng in coords],
color=staticmaps.BLUE,
width=4
)
context.add_object(line)
# Add start marker (green)
start_marker = staticmaps.Marker(
staticmaps.create_latlng(start_lat, start_lon),
color=staticmaps.GREEN,
size=12
)
context.add_object(start_marker)
# Add end marker (red)
end_marker = staticmaps.Marker(
staticmaps.create_latlng(end_lat, end_lon),
color=staticmaps.RED,
size=12
)
context.add_object(end_marker)
# Generate image and save to temp file
image = context.render_pillow(500, 375)
# Create unique temp file path
filename = f"route_{uuid.uuid4().hex[:8]}.webp"
filepath = os.path.join(TEMP_DIR, filename)
image.save(filepath, format='WEBP', quality=85, optimize=True)
return filepath
def load_image_with_title(image_path, custom_title=None):
"""Load image from path and optionally add custom title."""
image = Image.open(image_path)
if custom_title:
from PIL import ImageDraw, ImageFont
draw = ImageDraw.Draw(image)
# Try to use a nice font, fallback to default
try:
font = ImageFont.truetype("Arial.ttf", 24)
except:
font = ImageFont.load_default()
# Add title at top center
text_bbox = draw.textbbox((0, 0), custom_title, font=font)
text_width = text_bbox[2] - text_bbox[0]
x = (image.width - text_width) // 2
y = 10
# Add background rectangle for better readability
padding = 5
draw.rectangle([x-padding, y-padding, x+text_width+padding, y+text_bbox[3]+padding],
fill="white", outline="black")
draw.text((x, y), custom_title, fill="black", font=font)
return image