使用 python 进行图片压缩

关键词:python 、 图片压缩 、 image模块 、 os模块

开发环境:PyCharm

版本:python 3.9.5

效果图

压缩前大小


压缩后大小

关键代码

try:
    # 当前目录
    imgPath = r'{root}/'.format(**{'root': os.getcwd()})
    if os.path.exists(imgPath + '/img_new') == False:
        os.mkdir(imgPath + '/img_new')

    # 获取文件夹内文件
    path_list = ['img' + '\\' + i for i in os.listdir(imgPath + '\img')]
    # 循环图片进行压缩
    for path in path_list:
        im = Image.open(imgPath + path)
        (x,y) = im.size
        x_1 = x
        y_1 = int(y * x_1 / x) # 计算缩小后高度
        out = im.resize((x_1,y_1)) # 改变尺寸,保持图片高品质
        if out.mode == "RGBA":
            out = out.convert('RGB')
        #保存为jpg格式
        out.save(imgPath + 'img_new\\{}'.format(path.split('\\')[-1]))
    print('处理完成')
except Exception as e:
    print(e)

工具下载

https://pan.baidu.com/s/1v_pTvGvq0LYqnka9ceZXjg 提取码: 3gqu 复制这段内容后打开百度网盘手机App,操作更方便哦

完整代码

https://pan.baidu.com/s/1jHcLFF90JAKJeLIM4EI01A 提取码: 9smp 复制这段内容后打开百度网盘手机App,操作更方便哦

举报
评论 0