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 相关文章推荐
使用python加密自己的密码
Aug 04 Python
python基础教程项目四之新闻聚合
Apr 02 Python
selenium3+python3环境搭建教程图解
Dec 07 Python
python中return的返回和执行实例
Dec 24 Python
pytorch实现对输入超过三通道的数据进行训练
Jan 15 Python
Python中remove漏删和索引越界问题的解决
Mar 18 Python
使用卷积神经网络(CNN)做人脸识别的示例代码
Mar 27 Python
django执行原始查询sql,并返回Dict字典例子
Apr 01 Python
利用Python实现斐波那契数列的方法实例
Jul 26 Python
Python如何将将模块分割成多个文件
Aug 04 Python
python多线程爬取西刺代理的示例代码
Jan 30 Python
python中的sys模块和os模块
Mar 20 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去掉json字符串中的反斜杠\及去掉双引号前的反斜杠
2015/09/30 PHP
yii,CI,yaf框架+smarty模板使用方法
2015/12/29 PHP
windows下的WAMP环境搭建图文教程(推荐)
2017/07/27 PHP
PHP判断是否是微信打开,浏览器打开的方法
2018/03/14 PHP
PHP后期静态绑定之self::限制实例分析
2018/12/21 PHP
[转]JS宝典学习笔记
2007/02/07 Javascript
防止动态加载JavaScript引起的内存泄漏问题
2009/10/08 Javascript
jQuery Dialog 弹出层对话框插件
2010/08/09 Javascript
ajax处理php返回json数据的实例代码
2013/01/24 Javascript
JS删除数组元素的函数介绍
2013/03/27 Javascript
jquery选择器大全 全面详解jquery选择器
2014/03/06 Javascript
jquery easyui 结合jsp简单展现table数据示例
2014/04/18 Javascript
JS实现点击上移下移LI行数据的方法
2015/08/05 Javascript
JavaScript 弹出子窗体并返回结果到父窗体的实现代码
2016/05/28 Javascript
详解Angular 中 ngOnInit 和 constructor 使用场景
2017/06/22 Javascript
Angular.js通过自定义指令directive实现滑块滑动效果
2017/10/13 Javascript
微信小程序动态生成二维码的实现代码
2018/07/25 Javascript
微信小程序引用iconfont图标的方法
2018/10/22 Javascript
基于JavaScript canvas绘制贝塞尔曲线
2018/12/25 Javascript
vue 单页应用和多页应用的优劣
2020/10/22 Javascript
[58:21]DOTA2亚洲邀请赛 4.3 突围赛 Liquid vs VGJ.T 第二场
2018/04/04 DOTA
[04:03][TI9趣味短片] 小鸽子茶话会
2019/08/20 DOTA
python使用post提交数据到远程url的方法
2015/04/29 Python
深入解答关于Python的11道基本面试题
2017/04/01 Python
python实现定时提取实时日志程序
2018/06/22 Python
深入理解Django-Signals信号量
2019/02/19 Python
python实现二级登陆菜单及安装过程
2019/06/21 Python
python3实现二叉树的遍历与递归算法解析(小结)
2019/07/03 Python
django 多对多表的创建和插入代码实现
2019/09/09 Python
Python使用jupyter notebook查看ipynb文件过程解析
2020/06/02 Python
中国海淘族值得信赖的海淘返利网站:55海淘
2017/01/16 全球购物
英国第一家领先的在线处方眼镜零售商:Glasses Direct
2018/02/23 全球购物
瑞典香水、须后水和美容产品购物网站:Parfym-Klick.se
2019/12/29 全球购物
优秀实习自我鉴定
2013/12/04 职场文书
护理人员的自我评价分享
2014/03/15 职场文书
检举信的格式及范文
2014/04/04 职场文书