Home > Mobile >  How to add alphanumeric identifiers to the squares on a map with a grid
How to add alphanumeric identifiers to the squares on a map with a grid

Time:03-17

I have a 9728 x 9216 pixel .png file that represents a map. The map comprises a 128 x 128 pixel grid of lines, resulting in 76x72 squares. I would like to add addresses, from A1 to CU76 (did I get that right?), to each square in a small, light grey, slightly transparent font, and I'd rather not do it by hand. My computer is a Windows 10 desktop, I believe to have Java RT environment installed, but that's the full extent of it. My only experince in programming was a Pascal course on a mainframe in university, in 1987. Would anyone be so nice as to make a recommendation how I can get the above implemented?

CodePudding user response:

#!/usr/bin/env python3

import math
from PIL import Image, ImageDraw, ImageFont

input_filename = "***.bmp"
output_filename = "***.png"

cell_width = 128
cell_height = 128

line_color = [(255, 255, 255), (0, 0, 0)]

font_filename = "arial.ttf"
font_size = 16 # pt

text_offset_x = 4
text_offset_y = 2
text_fill = (255, 255, 255)
text_stroke = (0, 0, 0)
text_stroke_width = 1

def column_label(c):
    """Given 0-based index, generate label: A-Z, AA-ZZ, AAA-ZZZ, etc."""
    digits = []
    while c >= 26:
        d = c % 26
        c = c // 26 - 1
        digits.append(d)
    digits.append(c)
    letters = [chr(d   65) for d in reversed(digits)]
    return ''.join(letters)

with Image.open(input_filename).convert('RGB') as image:
    image_width, image_height = image.size
    rows = math.ceil(image_height / cell_height)
    columns = math.ceil(image_width / cell_width)
    
    draw = ImageDraw.Draw(image)
    
    # Outline around entire map
    draw.rectangle([0, 0, image_width - 1, image_height - 1],
                   outline=line_color[0])
    
    # Grid lines
    for i in [1, 0]:
        # Vertical lines
        for c in range(0, columns):
            x = i   c * cell_width
            draw.line([x, 0, x, image_height], fill=line_color[i])
        # Horizontal lines
        for r in range(0, rows):
            y = i   r * cell_height
            draw.line([0, y, image_width, y], fill=line_color[i])
        
    # Cell labels
    font = ImageFont.truetype(font_filename, font_size)
    for c in range(0, columns):
        c_label = column_label(c)
        for r in range(0, rows):
            x = text_offset_x   c * cell_width
            y = text_offset_y   r * cell_height
            label = "{}{}".format(c_label, r   1)
            draw.text((x, y), label, font=font, fill=text_fill,
                      stroke_fill=text_stroke, stroke_width=text_stroke_width)
    
    image.save(output_filename)

CodePudding user response:

This is thanks to a contributor/benefactor wanting to stay incognito

  • Related