python 批量压缩图片的脚本


Posted in Python onJune 02, 2021

简介

用Python批量压缩图片,把文件夹或图片直接拖入即可

需要 Needs

Python 3

Pillow (用pip install pillow来安装即可)

用法 Usage

把文件夹或图片直接拖入即可。如果拖入的是文件夹,则会遍历子文件夹把所有图片都压缩了。

注意,压缩后的文件会直接替换原来的文件,文件名不变,尺寸不变,只改变压缩质量。

文件的开头有两个变量:

SIZE_CUT = 4 表示大于4MB的图片都会进行压缩

QUALITY = 90 表示压缩质量90,这个质量基本人眼是看不出来啥差距的,而且很多原先10M的图能压缩一半。80以下的质量大概就不太行了。

代码

#!/usr/bin/python3
# -*- coding: UTF-8 -*-

# Created by Mario Chen, 01.04.2021, Shenzhen
# My Github site: https://github.com/Mario-Hero

import sys
import os
from PIL import Image

SIZE_CUT = 4   # picture over this size should be compressed. Units: MB
QUALITY = 90  # 90 is good, this number should not be smaller than 80.


def isPic(name):
    namelower = name.lower()
    return namelower.endswith("jpeg") or namelower.endswith("jpg") or namelower.endswith("png")


def compressImg(file):
    #print("The size of", file, "is: ", os.path.getsize(file))
    im = Image.open(file)
    im.save(file, quality=QUALITY)


def compress(folder):
    try:
        if os.path.isdir(folder):
            print(folder)
            file_list = os.listdir(folder)
            for file in file_list:
                if os.path.isdir(folder+"/"+file):
                    #print(folder +"/"+ file)
                    compress(folder +"/"+file)
                else:
                    if isPic(file):
                        if os.path.getsize(folder + "/" + file) > (SIZE_CUT * 1024 * 1024):
                            compressImg(folder + "/" + file)
                            print(file)
        else:
            if isPic(folder):
                if os.path.getsize(folder) > (SIZE_CUT * 1024 * 1024):
                    compressImg(folder)
    except BaseException:
        return


if __name__ == '__main__':
    for folder in sys.argv:
        #print(folder)
        compress(folder)
    print("Finish.")
    #os.system("pause")

实现效果

python 批量压缩图片的脚本

压缩后大小

python 批量压缩图片的脚本

另外一种图片压缩实现方式

同样自动遍历目录下的图片

import os
from PIL import Image
import threading,time

def imgToProgressive(path):
    if not path.split('.')[-1:][0] in ['png','jpg','jpeg']:  #if path isn't a image file,return
        return
    if os.path.isdir(path):
        return
##########transform img to progressive
    img = Image.open(path)
    destination = path.split('.')[:-1][0]+'_destination.'+path.split('.')[-1:][0]
    try:
        print(path.split('\\')[-1:][0],'开始转换图片')
        img.save(destination, "JPEG", quality=80, optimize=True, progressive=True) #转换就是直接另存为
        print(path.split('\\')[-1:][0],'转换完毕')
    except IOError:
        PIL.ImageFile.MAXBLOCK = img.size[0] * img.size[1]
        img.save(destination, "JPEG", quality=80, optimize=True, progressive=True)
        print(path.split('\\')[-1:][0],'转换完毕')
    print('开始重命名文件')
    os.remove(path)
    os.rename(destination,path)

for d,_,fl in os.walk(os.getcwd()):    #遍历目录下所有文件
    for f in fl:
        try:
            imgToProgressive(d+'\\'+f)
        except:
            pass

以上就是python 批量压缩图片的脚本的详细内容,更多关于python 批量压缩图片的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
简单的编程0基础下Python入门指引
Apr 01 Python
Python内置函数dir详解
Apr 14 Python
Django视图和URL配置详解
Jan 31 Python
Python配置虚拟环境图文步骤
May 20 Python
树莓派动作捕捉抓拍存储图像脚本
Jun 22 Python
python安装scipy的步骤解析
Sep 28 Python
python实现超市商品销售管理系统
Nov 22 Python
Python Numpy 自然数填充数组的实现
Nov 28 Python
将python文件打包exe独立运行程序方法详解
Feb 12 Python
Python安装whl文件过程图解
Feb 18 Python
基于打开pycharm有带图片md文件卡死问题的解决
Apr 24 Python
如何在python中实现线性回归
Aug 10 Python
python操作xlsx格式文件并读取
关于Numpy之repeat、tile的用法总结
Jun 02 #Python
Matlab如何实现矩阵复制扩充
Jun 02 #Python
给numpy.array增加维度的超简单方法
Jun 02 #Python
pytorch model.cuda()花费时间很长的解决
如何理解及使用Python闭包
python pygame入门教程
You might like
PHP 图像尺寸调整代码
2010/05/26 PHP
php strnatcmp()函数的用法总结
2013/11/27 PHP
php上传图片到指定位置路径保存到数据库的具体实现
2013/12/30 PHP
百度工程师讲PHP函数的实现原理及性能分析(三)
2015/05/13 PHP
PHP的运行机制与原理(底层)
2015/11/16 PHP
php cookie工作原理与实例详解
2016/07/18 PHP
教你在header中隐藏php的版本信息
2016/08/10 PHP
thinkPHP5框架分页样式类完整示例
2018/09/01 PHP
PHP的new static和new self的区别与使用
2019/11/27 PHP
PHP pthreads v3使用中的一些坑和注意点分析
2020/02/21 PHP
pjblog修改技巧汇总
2007/03/12 Javascript
Array.prototype 的泛型应用分析
2010/04/30 Javascript
40款非常棒的jQuery 插件和制作教程(系列二)
2011/11/02 Javascript
web的各种前端打印方法之jquery打印插件jqprint实现网页打印
2013/01/09 Javascript
JS下拉缓冲菜单示例代码
2013/08/30 Javascript
Javascript数组操作函数总结
2015/02/05 Javascript
浅谈JavaScript字符串与数组
2015/06/03 Javascript
js日期插件dateHelp获取本月、三个月、今年的日期
2016/03/07 Javascript
javascript history对象详解
2017/02/09 Javascript
浅谈es6中export和export default的作用及区别
2018/02/07 Javascript
JS中getElementsByClassName与classList兼容性问题解决方案分析
2019/08/07 Javascript
javascript/jquery实现点击触发事件的方法分析
2019/11/11 jQuery
Vuex实现购物车小功能
2020/08/17 Javascript
antd多选下拉框一行展示的实现方式
2020/10/31 Javascript
Python 元类使用说明
2009/12/18 Python
浅谈python装饰器探究与参数的领取
2017/12/01 Python
Tensorflow分类器项目自定义数据读入的实现
2019/02/05 Python
python next()和iter()函数原理解析
2020/02/07 Python
Python3.7.0 Shell添加清屏快捷键的实现示例
2020/03/23 Python
python一些性能分析的技巧
2020/08/30 Python
英国最大的高品质珠宝和手表专家:Goldsmiths
2017/03/11 全球购物
师范大学毕业自我鉴定
2013/11/21 职场文书
人事经理岗位职责
2014/04/28 职场文书
应届生求职信范文
2014/06/30 职场文书
2015年环卫处个人工作总结
2015/07/27 职场文书
Python中如何处理常见报错
2022/01/18 Python