1、导入所需的包
import os
from PIL import Image
2、获取源图片
path_img = 'image'
img_dir = os.listdir(path_img)
3、循环读取源图片并按指定宽高进行自动截图保存
for i in range(len(img_dir)):id = img_dir[i].split('.')[0]img = Image.open(path_img + '/' + img_dir[i])size_img = img.sizeprint(size_img)weight = int(size_img[0])height = int(size_img[1] // 3) + 155for j in range(2):for k in range(1):box = (weight * k, height * j, weight * (k + 1), height * (j + 1))region = img.crop(box)region.save('newimg\\''{}-{}{}.png'.format(id, j, k))
这两行代码主要用来获取截取图片的宽高,代码默认宽按原图片宽,高按原图片高除以3加顶部空白区域的高155像素。
完整代码下:
import os
from PIL import Imagepath_img = 'image'
img_dir = os.listdir(path_img)
print(img_dir)
print(len(img_dir))
for i in range(len(img_dir)):id = img_dir[i].split('.')[0]img = Image.open(path_img + '/' + img_dir[i])size_img = img.sizeprint(size_img)weight = int(size_img[0])height = int(size_img[1] // 3) + 155for j in range(2):for k in range(1):box = (weight * k, height * j, weight * (k + 1), height * (j + 1))region = img.crop(box)region.save('newimg\\''{}-{}{}.png'.format(id, j, k))