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 相关文章推荐
web.py获取上传文件名的正确方法
Aug 26 Python
python模拟Django框架实例
May 17 Python
Python单元测试实例详解
May 25 Python
Python如何爬取实时变化的WebSocket数据的方法
Mar 09 Python
详解python的argpare和click模块小结
Mar 31 Python
Django框架使用内置方法实现登录功能详解
Jun 12 Python
python Tcp协议发送和接收信息的例子
Jul 22 Python
Django+zTree构建组织架构树的方法
Aug 21 Python
jenkins配置python脚本定时任务过程图解
Oct 29 Python
Python 过滤错误log并导出的实例
Dec 26 Python
Python小整数对象池和字符串intern实例解析
Mar 21 Python
TensorFlow keras卷积神经网络 添加L2正则化方式
May 22 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
从MySQL数据库表中取出随机数据的代码
2007/09/05 PHP
PHP中fwrite与file_put_contents性能测试代码
2013/08/02 PHP
PHP判断是否是微信打开还是浏览器打开的方法
2019/02/27 PHP
vue的props实现子组件随父组件一起变化
2016/10/27 Javascript
jQuery实现在HTML文档加载完毕后自动执行某个事件的方法
2017/05/08 jQuery
详解vue-router 2.0 常用基础知识点之router.push()
2017/05/10 Javascript
js实现首屏延迟加载实现方法 js实现多屏单张图片延迟加载效果
2017/07/17 Javascript
input type=file 选择图片并且实现预览效果的实例
2017/10/26 Javascript
Vue-router路由判断页面未登录跳转到登录页面的实例
2017/10/26 Javascript
Bootstrap框架建立树形菜单(Tree)的实例代码
2017/10/30 Javascript
vue2单元测试环境搭建
2018/05/24 Javascript
详解React 的几种条件渲染以及选择
2018/10/23 Javascript
微信小程序实现随机验证码功能
2018/12/20 Javascript
Vue+Koa2+mongoose写一个像素绘板的实现方法
2019/09/10 Javascript
javascript sort()对数组中的元素进行排序详解
2019/10/13 Javascript
ES6 Generator基本使用方法示例
2020/06/06 Javascript
深入理解javascript中的this
2021/02/08 Javascript
[01:20:37]FNATIC vs NIP 2019国际邀请赛小组赛 BO2 第一场 8.16
2019/08/19 DOTA
python实现的各种排序算法代码
2013/03/04 Python
Python获取暗黑破坏神3战网前1000命位玩家的英雄技能统计
2016/07/04 Python
儿童编程python入门
2018/05/08 Python
DJango的创建和使用详解(默认数据库sqlite3)
2019/11/18 Python
使用python实现多维数据降维操作
2020/02/24 Python
Python解释器以及PyCharm的安装教程图文详解
2020/02/26 Python
Python PyQt5模块实现窗口GUI界面代码实例
2020/05/12 Python
详解向scrapy中的spider传递参数的几种方法(2种)
2020/09/28 Python
Python爬虫之Selenium警告框(弹窗)处理
2020/12/04 Python
CSS3实现瀑布流布局与无限加载图片相册的实例代码
2016/12/22 HTML / CSS
HTML5触摸事件实现移动端简易进度条的实现方法
2018/05/04 HTML / CSS
adidas泰国官网:adidas TH
2020/07/11 全球购物
局部内部类是否可以访问非final变量?
2013/04/20 面试题
求职简历中个人的自我评价
2013/12/25 职场文书
企业指导教师评语
2014/04/28 职场文书
一年级语文下册复习计划
2015/01/17 职场文书
Keras多线程机制与flask多线程冲突的解决方案
2021/05/28 Python
python3实现常见的排序算法(示例代码)
2021/07/04 Python