首页 > 解决方案 > 如何给数字一个特定的颜色并使用 PIL 显示它?

问题描述

我一直在开发基于图块的游戏,我想知道是否有一种方法可以仅从带有数字的文件中制作地图。我有一个文件“map.txt”,其中是代表每个图块的数字。这些数字(图块)根据图块具有不同的颜色。

例如:

0   0   1   1   1   1   0   1   2   2   2
0   1   2   2   1   1   0   0   0   1   0
0   0   1   1   1   1   0   1   2   2   2

0 - 黑色

1 - 黄色

2 - 绿色

我想使用 PIL 制作一张地图,其中每个图块都表示为一个像素并将其保存为图像。我已经看到它使用 pygame 完成,但我希望它只使用 PIL。

谢谢回复。

标签: python-3.xpython-imaging-library

解决方案


您可以通过使用带有模式 P的图像来实现这一点,即使用调色板的图像。

基本的工作流程将是:

  • 读取文本文件,提取所有数字连续列表。
  • 根据行数和总数确定地图图像的宽度和高度。
  • 使用模式创建一个新Image对象。PImage.new
  • 使用 设置从获得的数字列表中的图像数据Image.putdata
  • 为所需的颜色数量设置适当的调色板,并使用Image.putpalette.

这就是整个代码:

from PIL import Image

# Read map data from text file
with open('map.txt') as f:
    lines = f.readlines()

# Extract numbers from map data to continuous list of integers
imdata = [int(x) for line in lines for x in line if x.isdigit()]

# Get image dimensions
h = len(lines)
w = len(imdata) // h

# Create new image of correct size with mode 'P', set image data
img = Image.new('P', (w, h), 0)
img.putdata(imdata)

# Set up and apply palette data
img.putpalette([  0,   0,   0,          # Black
                255, 255,   0,          # Yellow
                  0, 255,   0])         # Green

# Save image
img.save('map.png')

而且,这将是输出图像:

地图

如果你也愿意使用 NumPy,代码可以缩短:

import numpy as np
from PIL import Image

# Extract numbers from map data to NumPy array
imdata = np.loadtxt('map.txt').astype(np.uint8)

# Create new image from NumPy array with mode 'P'
img = Image.fromarray(imdata, 'P')

# Set upand apply palette data
img.putpalette([  0,   0,   0,          # Black
                255, 255,   0,          # Yellow
                  0, 255,   0])         # Green

# Save image
img.save('map.png')
----------------------------------------
System information
----------------------------------------
Platform:      Windows-10-10.0.16299-SP0
Python:        3.9.1
PyCharm:       2021.1.1
NumPy:         1.20.2
Pillow:        8.2.0
----------------------------------------

推荐阅读