python-3.x - 如何给数字一个特定的颜色并使用 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。
谢谢回复。
解决方案
您可以通过使用带有模式 P
的图像来实现这一点,即使用调色板的图像。
基本的工作流程将是:
- 读取文本文件,提取所有数字连续列表。
- 根据行数和总数确定地图图像的宽度和高度。
- 使用模式创建一个新
Image
对象。P
Image.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
----------------------------------------
推荐阅读
- spring-boot - 如何将布尔数据库值映射到 Java 枚举
- php - 这个功能是安全的还是更安全,如果是的话如何
- python-3.x - 获取 N 项的所有组合
- .net-core - .net 核心中的 HttpClientHandler 不包含客户端证书
- python - itertools 产品功能列表中的两个元素
- cocoa - NS 定时器更新文本字段
- c# - 过滤 ICollectionView 以根据搜索词的存在时间对字符串进行排序
- java - 我想创建用户和角色实体类,但 @Column 注释要求数据源?
- r - 安装 R 包时出错?
- javascript - 我想将 JSON 数据从 node-fetch api 发送到浏览器并每 900 毫秒更新一次数据。我怎样才能做到这一点?