用python给做个自动切图工具的示例
```python
# -*- coding: utf-8 -*-
import os, sys
from PIL import Image
def cut_image(image): # 定义切图函数
width = image.size[0] # 获取图片宽度和高度
height = image.size[1]
item_width = int(width / 3) # 因为是3x3的网格,所以每一份的宽度是总宽度除以3
box_list = [] # 存储切割后的小图片位置,元组格式:(左上角x坐标,左上角y坐标,右下角x坐标,右下角y坐标 )
for i in range(0,3): # 0 1 2 三行
for j in range(0,3): # 0 1 2 三列
box = (j * item_width, i * item_width, (j + 1) * item_width, (i + 1) * item_width) # 计算每一个小图片的位置信息
box_list.append(box) # 把位置信息存储到box——list中去
image_list = [image.crop(box) for box in box_list] # 根据位置信息进行切割(PIL中有一个crop函数可以进行切割)
return image_list # 返回分割后的小图片集合
if __name__ == '__main__': # 程序入口处理部分代码如下所示。
fileName='./test.png' # 需要处理的文件名字 # 由于该文件在当前目录中所以不用写具体路径。 if os.path.isfile(fileName): # 先看看该文件是不是存在 try: img=Image.open(fileName) imgList=cutImage(img); n=1; for imgeItem in imgList: imgeItem.save('result'+str(n)+'.jpg'); n+=1; except Exception as e : print('Error:',e); else : print("%s is not exist!" % fileName); else : print("%s is not a file!" % fileName); sys.exit(); print("Done");```
免责声明:
以上内容除特别注明外均来源于网友提问,创作工场回答,未经许可,严谨转载。