python 批量压缩文件,只改变了宽高

该代码实现了一个图片处理功能,检查图片尺寸和大小,若超过设定阈值则进行压缩,否则直接复制。使用PIL库进行图片操作,同时具备异常处理,确保遇到损坏图片时仍能继续执行。适用于大量图片的批量处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import os
import imghdr
from PIL import Image
# path是文件读取路径,save_path是保存路径
def handle_image(path,sub_path,file):
    im = Image.open(path)
    # im.show()
    (x, y) = im.size # 读取图片大小
    # 图片的长宽变为原来的2分之1
    # new_x = 1920
    # new_y = round(y/x*1920)
    size=os.path.getsize(path)#获取文件大小
    if x > 2000 and size >2000000 :#限定图片宽度大于1000像素,并且大于1MB的财才进行处理
        new_x = x//2
        new_y = y//2
        out = im.resize((new_x, new_y), Image.ANTIALIAS)
        newfile = file.replace('.', '_resize.')  # 修改文件名
        savepath = os.path.join(sub_path, newfile)  # 用文件名拼接保存路径
        out.save(savepath)
        print('%s压缩处理完成' % savepath)

    # 如果图片尺寸或者大小不满足压缩条件直接复制
    else:
        savepath = os.path.join(sub_path, file)  # 用文件名拼接保存路径
        f1 = open(path, 'rb')
        f2 = open(savepath, 'wb')
        while True:
            file = f1.read()
            if file:
                f2.write(file)
            else:
                print('%s未做处理,直接复制'%savepath)
                break

# root_path=r'C:\Users\wangjinyu\Desktop\myimage'#原始文件路径
root_path=r'C:\Users\Administrator\Desktop\newimg'#原始文件路径
# new_path = r'C:\Users\wangjinyu\Desktop\new'#要拷贝到的新路径
new_path = r'C:\Users\Administrator\Desktop\oldimg1'#要拷贝到的新路径
for root, dirs, files in os.walk(root_path):
    # print(root)
    # print(dirs)
    new_root_path = root.split(root_path)[1]#生成拼接的路径
    os.mkdir(new_path + new_root_path)#在新路径创建对应文件夹
    sub_path=new_path + new_root_path#获取刚创建的文件夹路径
    for  file in files:
        file_path=os.path.join(root,file)
        # print(root)
        if imghdr.what(file_path) is not None:#判断是不是图片文件,如果不是图片就会返回None
            #加异常处理,有时候碰到损坏的图片会报错,程序就停了,加完异常处理就可以继续执行了
            try:
                handle_image(file_path,sub_path,file)#更改文件尺寸并保存到新路径
            except:
                print('%s处理异常'%file_path)
            else:
                pass

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值