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解析JSON数据的基本方法
Oct 15 Python
Python中 Lambda表达式全面解析
Nov 28 Python
Python中循环引用(import)失败的解决方法
Apr 22 Python
Python面向对象类的继承实例详解
Jun 27 Python
Flask框架web开发之零基础入门
Dec 10 Python
Python中使用pypdf2合并、分割、加密pdf文件的代码详解
May 21 Python
python 实现在一张图中绘制一个小的子图方法
Jul 07 Python
python实现PCA降维的示例详解
Feb 24 Python
python topk()函数求最大和最小值实例
Apr 02 Python
Django 解决由save方法引发的错误
May 21 Python
使用python实现下载我们想听的歌曲,速度超快
Jul 09 Python
Python如何输出百分比
Jul 31 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文件打开、关闭、写入的判断与执行代码
2011/05/24 PHP
php版微信开发之接收消息,自动判断及回复相应消息的方法
2016/09/23 PHP
php从数据库中获取数据用ajax传送到前台的方法
2018/08/20 PHP
对YUI扩展的Gird组件 Part-2
2007/03/10 Javascript
jQuery 阴影插件代码分享
2012/01/09 Javascript
JavaScript中的apply()方法和call()方法使用介绍
2012/07/25 Javascript
jquery中常用的SET和GET$(”#msg”).html循环介绍
2013/10/09 Javascript
jquery实现弹出div,始终显示在屏幕正中间的简单实例
2014/03/08 Javascript
js,jquery滚动/跳转页面到指定位置的实现思路
2014/06/03 Javascript
jQuery实现两款有动画功能的导航菜单代码
2015/09/16 Javascript
node.js中 stream使用教程
2016/08/28 Javascript
vue.js学习之vue-cli定制脚手架详解
2017/07/02 Javascript
vue cli 全面解析
2018/02/28 Javascript
详解Vue中数组和对象更改后视图不刷新的问题
2018/09/21 Javascript
angularJs使用ng-repeat遍历后选中某一个的方法
2018/09/30 Javascript
Javascript数组方法reduce的妙用之处分享
2019/06/10 Javascript
python获取当前计算机cpu数量的方法
2015/04/18 Python
Python3 处理JSON的实例详解
2017/10/29 Python
python实现自动解数独小程序
2019/01/21 Python
Python多线程原理与用法实例剖析
2019/01/22 Python
python中字符串数组逆序排列方法总结
2019/06/23 Python
tensorflow 实现从checkpoint中获取graph信息
2020/02/10 Python
css3实例教程 一款纯css3实现的发光屏幕旋转特效
2014/12/07 HTML / CSS
html5的自定义data-*属性与jquery的data()方法的使用
2014/07/02 HTML / CSS
Canvas系列之滤镜效果
2019/02/12 HTML / CSS
canvas实现烟花的示例代码
2020/01/16 HTML / CSS
一个精品风格的世界:Atterley
2019/05/01 全球购物
万代美国官网:PREMIUM BANDAI USA
2020/09/11 全球购物
职称自我鉴定
2013/10/15 职场文书
早会主持词
2014/03/17 职场文书
《画家乡》教学反思
2014/04/22 职场文书
小学校园之星事迹材料
2014/05/16 职场文书
求职信名称怎么写
2014/05/26 职场文书
签约仪式致辞
2015/07/30 职场文书
安全生产标语口号
2015/12/26 职场文书
六年级作文之关于梦
2019/10/22 职场文书