You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python PIL将对应物品类型的二维数组转换为emoji图片

实现方案

完全可以实现,核心思路是提前定义数字和emoji的映射规则,按二维数组的行列遍历,用PIL的文字渲染能力把对应emoji画到网格的对应位置即可。

前置依赖

先安装Pillow库:

pip install pillow

注意事项

默认系统字体大多不支持彩色emoji渲染,需要使用专门的emoji字体,不同系统的内置emoji字体路径如下:

  • Windows:C:\Windows\Fonts\seguiemj.ttf
  • Mac:/System/Library/Fonts/Apple Color Emoji.ttc
  • Linux:/usr/share/fonts/truetype/noto/NotoColorEmoji.ttf(需提前安装noto-color-emoji软件包)
    如果找不到对应字体,也可以自行下载开源emoji字体放到项目目录中引用。

完整代码

from PIL import Image, ImageDraw, ImageFont

# 数字和emoji的映射规则
EMOJI_MAP = {
    0: "⬜",
    1: "🧱",
    2: "📦",
    3: "🎯",
    4: "🧑"
}

# 配置参数
CELL_SIZE = 64  # 每个格子的像素大小
FONT_SIZE = int(CELL_SIZE * 0.8)  # emoji字体大小

# 待转换的二维数组
game_map = [
    [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
    [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
    [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
    [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
    [1, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 3, 1],
    [1, 0, 0, 0, 0, 0, 2, 4, 2, 0, 0, 0, 2, 0, 1],
    [1, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 1],
    [1, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 1],
    [1, 0, 3, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
    [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
]

# 初始化画布
rows = len(game_map)
cols = len(game_map[0])
img = Image.new("RGB", (cols * CELL_SIZE, rows * CELL_SIZE), "white")
draw = ImageDraw.Draw(img)

# 加载字体,替换为你系统对应的emoji字体路径
font = ImageFont.truetype("C:\Windows\Fonts\seguiemj.ttf", size=FONT_SIZE)

# 遍历渲染每个格子
for y in range(rows):
    for x in range(cols):
        current_emoji = EMOJI_MAP[game_map[y][x]]
        # anchor=mm 表示文字居中对齐
        draw.text(
            (x * CELL_SIZE + CELL_SIZE//2, y * CELL_SIZE + CELL_SIZE//2),
            current_emoji,
            font=font,
            fill="black",
            anchor="mm"
        )

# 保存图片
img.save("game_map.png")
print("地图图片已生成,保存路径:./game_map.png")

可调参数

你可以根据自己的需求调整以下参数:

  • CELL_SIZE:修改每个格子的大小,值越大生成的图片越大
  • EMOJI_MAP:更换为你想要的emoji样式
  • 画布背景色:修改Image.new的第三个参数即可

内容的提问来源于stack exchange,提问作者Aspect11

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 22:00:00