import os
import shutil
from PIL import Image
# 获取path目录下的所有文件
def get_imlist(path):
return [os.path.join(path, f) for f in os.listdir(path)]
def cut_img(path="demo"):
paths = path +"/"
# 判断一下用于储存裁切后的文件夹是否存在 存在删除,不存在创建
if os.path.exists(paths):
shutil.rmtree(path)
os.mkdir(path)
else:
os.mkdir(path)
# 获取上传路径内的文件列别
directorys = get_imlist(paths)
for directory in directorys:
# 判断不是图片文件就跳过(我这里只处理jpg和png的图片 也可以加上jpeg的)
if not (directory.endswith('.jpg') or directory.endswith('.png')):
pass
else:
s = "/"
try:
img = Image.open(directory)
# 提取源图片的名字 用不裁切后的图片名字使用
oimage_name = directory[directory.rfind(s) + 1:]
(oimage_width, oimage_height) = img.size
# 根据图片的宽和高,截取所需要的图片尺寸
l = int(oimage_width / 40) # 左边裁剪掉多少像素
u = int(oimage_height / 9) # 上边裁剪掉多少像素
r = 39 * int(oimage_width / 40) # 右边裁剪掉多少像素
d = 39 * int(oimage_height / 40)# 下边裁剪掉多少像素
# 获取到新的图片对象
cropped = img.crop((l, u, r, d))
# 保存到新的路径下
cropped.save("./" + paths + "/" + "%s" % oimage_name)
except:
# 异常处理 为了保证图片数量和裁剪前一直,把出错的图片也放到裁剪后的文件夹中,也可以换成一个新的文件夹
oimage_name = directory[directory.rfind(s) + 1:]
with open(directory, "rb") as f:
response = f.read()
with open("./" + paths + "/" + "%s" % oimage_name, "wb") as f1:
f1.write(response)
if __name__ == '__main__':
# 传入你的图片文件路径
cut_img("./path")
一篇文章搞懂python图片裁切的问题
最新推荐文章于 2024-08-27 20:46:01 发布