PIL
切割使用的Python PIL库的 Image.crop
示例:
from PIL import Image
im = Image.open("hopper.jpg")
(left, upper, right, lower) = (20, 20, 100, 100)
im_crop = im.crop((left, upper, right, lower))
left 距离左边 边距 可看做x坐标
upper 距离右边边距 可看做 y坐标
right > 另一个距离左边 边距 可看做x + width 坐标
lower 另一个距离右边边距 可看做 y + height 坐标
因此必须遵守如下规则 :
right > left
lower > upper
API
示例代码
# -*-coding utf8 -*-
from PIL import Image
import json
import os
# 读取配置解析数据
def decodeJson ():
path = 'res/scenery.json'
json_str = ''
f = open(path, "r", encoding="utf-8")
json_str = f.read()
# 转换为字典
obj = json.loads(json_str)
return obj
# 切割图片
def split(jsonData):
# 当前目录
wd = os.getcwd()
img = Image.open(jsonData['file'])
width = jsonData['width']
heigth = jsonData['heigth']
texture = jsonData['texture']
id = jsonData['id']
for key in texture:
item = texture[key]
item_x = item[ "x"]
item_y = item[ "y"]
item_width = item[ "width"]
item_height = item[ "height"]
box = (item_x,item_y,item_x + item_width ,item_y + item_height)
regx = img.crop(box)
if not os.path.exists(wd + '/cut'):
os.makedirs(wd + '/cut')
if not os.path.exists(wd + '/cut/'+id):
os.makedirs(wd + '/cut/'+id)
item_img = wd+ "/cut/"+id +"/"+ key + ".png"
regx.save(item_img)
print('split '+jsonData['file'] +' end ' )
def main():
print('decode res')
jsonData = decodeJson()
split(jsonData)
if __name__ == '__main__':
main()
网友评论