如何将字母数字标识符添加到带有网格的地图上的正方形中



我有一个9728 x 9216像素的.png文件,它表示地图。该地图由128 x 128像素的网格线组成,形成76x72个正方形。

我想用浅灰色、略带透明的小字体将地址从A1添加到CU76(我做对了吗?(,添加到每个正方形中,我不想手动添加。我的电脑是Windows 10台式机,我相信安装了Java RT环境,但这只是它的全部内容。我唯一的编程经验是1987年在大学里的大型机上学习Pascal课程。

这个python脚本实现了我的要求,这要归功于一位不愿透露姓名的捐助者

!/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)

最新更新