Python PIL.Image 图片操作
from PIL import Image
path = './test.png'
# 加载图片
im = Image.open(path)
# 显示图片
im.show()
# 图片大小
w, h = im.size
x, y = 0, 0
box = (x*w, y*h, (x+1)*w, (y+1)*h)
# 切片
piece = im.crop(box)
# 修改大小
new = im.resize(w*2,h*2)
# 保存
piece.save(path)
图片切割
import os
from PIL import Image
from tkinter import filedialog
def mkdir(path):
if not os.path.exists(path):
os.makedirs(path)
def cutImage(path_file, w, h):
path_dir = os.path.dirname(path_file)
new_dir = os.path.join(path_dir, 'test')
mkdir(new_dir)
im = Image.open(path_file)
tw, th = im.size
for x in range(int(tw/w)):
for y in range(int(th/h)):
piece = im.crop((x*w, y*h, (x+1)*w, (y+1)*h))
piece = piece.resize((w*2, h*2))
piece.save(new_dir+'/'+str(y)+'_'+str(x)+'.png', 'png')
if __name__ == '__main__':
path_file = filedialog.askopenfilename(initialdir='.')
print(path_file)
if path_file:
cutImage(path_file, 24, 24)