利用python脚本拆解游戏中的图集资源

如何使用Python对图集进行裁剪并保存,以便在开发游戏、UI设计等领域中使用。

以下是具体的步骤:

在运行这个脚本之前,需要确保你的Python环境中已经安装了以下库:

Pillow:用于图像处理和操作,可以通过pip install Pillow命令进行安装;

biplist:用于读取和写入plist文件,可以通过pip install biplist命令进行安装。

准备文件路径参数

首先需要准备好图集和plist文件的路径,以及裁剪后图片保存的路径。

1
2
3
plist_path = '/Users/您的电脑名字/Desktop/yuobm/map.plist'
img_path = '/Users/您的电脑名字/Desktop/yuobm/map.png'
save_path = '/Users/您的电脑名字/Desktop/yuobm/frames'

加载图集信息

使用biplist库读取plist文件,并获取图集文件名。

1
2
3
4
with open(plist_path, 'rb') as fp:
root = biplist.readPlist(fp)
file_name = img_path
image = Image.open(file_name)

遍历所有图片信息并裁剪保存

循环遍历所有图片信息,获取当前图片的名称和信息,并根据信息进行裁剪并保存。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
for image_info in root['frames']:
image_name = os.path.splitext(image_info)[0] + ".png"
info = root['frames'][image_info]['frame']

frame_str = info
x = int(frame_str[2:frame_str.index(',', 2)])
y = int(frame_str[frame_str.index(',', 2) + 1:frame_str.index('}', 2)])
width = int(frame_str[frame_str.rindex('{') + 1:frame_str.rindex(',', frame_str.rindex('{'))])
height = int(frame_str[frame_str.rindex(',') + 1:-2])

rotated = root['frames'][image_info].get('rotated', False)
if rotated:
crop_image = image.crop((x, y, x + height, y + width))
crop_image = crop_image.transpose(Image.ROTATE_90)
else:
crop_image = image.crop((x, y, x + width, y + height))

save_file = os.path.join(save_path, image_name)
crop_image.save(save_file)

以下是所有python的详细脚本:

里面的plist_path、img_path、save_path等需要换成你自己的路径。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
from PIL import Image
import os
import biplist

# 文件路径参数
plist_path = '/Users/xxx/Desktop/yuobm/map.plist'
img_path = '/Users/xxx/Desktop/yuobm/map.png'
save_path = '/Users/xxx/Desktop/yuobm/frames'

# 加载图集信息
with open(plist_path, 'rb') as fp:
root = biplist.readPlist(fp)

# 获取图集文件名
file_name = img_path

# 加载图集
image = Image.open(file_name)

if not os.path.exists(save_path):
os.makedirs(save_path)

# 循环遍历所有图片信息
for image_info in root['frames']:
# 获取当前图片的名称和信息
image_name = os.path.splitext(image_info)[0] + ".png"
info = root['frames'][image_info]['frame']

# 裁剪并保存图片
frame_str = info
x = int(frame_str[2:frame_str.index(',', 2)])
y = int(frame_str[frame_str.index(',', 2) + 1:frame_str.index('}', 2)])
width = int(frame_str[frame_str.rindex('{') + 1:frame_str.rindex(',', frame_str.rindex('{'))])
height = int(frame_str[frame_str.rindex(',') + 1:-2])

rotated = root['frames'][image_info].get('rotated', False)
if rotated:
# 需要旋转90度
crop_image = image.crop((x, y, x + height, y + width))
crop_image = crop_image.transpose(Image.ROTATE_90)
else:
crop_image = image.crop((x, y, x + width, y + height))

save_file = os.path.join(save_path, image_name)
crop_image.save(save_file)

总结

这就是使用Python对图集进行裁剪并保存的方法。通过以上步骤,可以实现快速、高效地处理图集资源。