Issue
I've been working on a tile-based game and I wanted to know if there is a way I could make a map from just a file with numbers. I have a file "map.txt" within which are numbers representing each tile. These numbers(tiles) have different colors depending on the tile.
For Example:
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 - Black
1 - Yellow
2 - Green
I want to use PIL to make a map in which each tile gets represented as a pixel and save it as an image. I've seen it done using pygame but I want it using just PIL.
Thanks for the reply.
Solution
You can achieve that by using an image with mode P
, i.e. an image using a palette.
The basic workflow then would be:
- Read text file, extract all numbers a continuous list.
- Determine width and height of map image from number of lines and total count of numbers.
- Create a new
Image
object with modeP
usingImage.new
. - Set image data from the obtained list of numbers using
Image.putdata
. - Set up a proper palette for the desired number of colors, and apply that palette using
Image.putpalette
.
That'd be the whole code:
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')
And, that'd be the output image:
If you're willing to also use NumPy, the code could be shortened:
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
----------------------------------------
Answered By - HansHirse
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.