import os
from PIL import Image
# 2022-10-03
class imgcut():
def getpaths(self):
'''输入目录,返回图片的绝对路径列表'''
while True:
dir=input('请输入目录路径: ')
paths=[]
for f in os.listdir(dir):
if f.endswith(('.png','.jpg','.jpeg','.gif')) :
paths.append(f)
if paths==():
print('路径错误或者当前路径没有图片,请重新输入: ')
continue
print('识别到的文件:\n', paths)
return dir,paths
def crop(self):
dir,paths=self.getpaths()
x,y=input('请输入长和宽(空格隔开): ').split()
x,y=int(x),int(y)
# x,y过大会补充图片
for path in paths:
img = Image.open(os.path.join(dir,path))
x0, y0 = img.size
box = [(x0 - x) // 2, (y0 - y) // 2, (x0 + x) // 2, (y0 + y) // 2] #centercrop
imgnew=img.crop(box)
name,ext=os.path.splitext(path)
savedir,savename=dir+'\\crop\\',name+'_'+ext
if not os.path.exists(savedir):
os.makedirs(savedir)
imgnew.save(savedir+savename)
print('save:',savedir+savename)
pass
def resize(self):
dir,paths=self.getpaths()
x,y=input('请输入长和宽(空格隔开,若等比例缩放另其中一个为-1): ').split()
x,y=int(x),int(y)
# x,y过大会补充图片
for path in paths:
img = Image.open(os.path.join(dir,path))
x0,y0=img.size
x=int(y/y0*x0) if x==-1 else x
y=int(x/x0*y0) if y==-1 else y
imgnew=img.resize((x,y),Image.ANTIALIAS)#NEAREST,BILINEAR,LANCZOS,ANTIALIAS
name,ext=os.path.splitext(path)
savedir,savename=dir+'\\',name+'_'+ext
if not os.path.exists(savedir):
os.makedirs(savedir)
imgnew.save(savedir+savename)
print('save:',savedir+savename)
pass
def menu(self):
print('格式需要再添加')
print('默认采用中心裁剪')
while True:
print('-----------------------')
print('1. 图片裁剪')
print('2. 图片伸缩')
print('-1. 退出')
c=input()
if c=='1':
self.crop()
elif c=='2':
self.resize()
elif c=='-1':
break
else:
print('请重新输入:')
def custom(self):
pass
imgcut().menu()
标签:paths,批量,剪辑,savedir,print,path,os,pillow,dir
From: https://www.cnblogs.com/wqzz/p/16750175.html