一篇文章搞懂python图片裁切的问题


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")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值