Python 批量压缩图片

By | May 31, 2021

方法1: 10 行 Python 代码,批量压缩图片 500 张

Tinypng 网站提供在线图片压缩服务,是所有图片压缩工具中最好用的之一,但它有所限制:批量最多处理 20 张,且每张大小不允许超过 5 M.

但是这个网站非常良心,开放了免费的 API,API 取消了每张大小的限制,只限定每个月处理 500 张图片.

下面介绍怎么使用它.第一步是在它网站上注册,获得专属的 API_KEY.使用的是邮箱注册,很简单.

然后是安装 package:

pip install tinify

接着是处理图片:

import tinify
import os

tinify.key = '此处填入你的key'
path = "C:\\Users\\yunpoyue\\Pictures\\cat" # 图片存放的路径

for dirpath, dirs, files in os.walk(path):
    for file in files:
        imgpath = os.path.join(dirpath, file)
        print("compressing ..."+ imgpath)
        tinify.from_file(imgpath).to_file(imgpath)

不到 10 行代码,轻轻松松就批量压缩图片,简直不要太爽!20 M 的图片能压缩到 2 M,压缩率达到惊人的 90%,成绩喜人.

它的 API 还提供图片裁剪,加水印,保存压缩图片至云服务商(亚马逊云、谷歌云)等功能,非常强大,除了压缩过程有点慢,其它无可挑剔!

此方法不支持压缩Gif等动态图片!
转载: https://mp.weixin.qq.com/s/5hpFDgjCpfb0O1Jg-ycACw

方法2: 需要安装第三方模块PIL

#coding:utf-8
from PIL import Image
import os

#图片压缩批处理  
def compressImage(srcPath,dstPath):  
    for filename in os.listdir(srcPath):  
        #如果不存在目的目录则创建一个,保持层级结构
        if not os.path.exists(dstPath):
                os.makedirs(dstPath)        

        #拼接完整的文件或文件夹路径
        srcFile=os.path.join(srcPath,filename)
        dstFile=os.path.join(dstPath,filename)
        print(srcFile)
        print(dstFile)

        #如果是文件就处理
        if os.path.isfile(srcFile):    
            #打开原图片缩小后保存,可以用if srcFile.endswith(".jpg")或者split,splitext等函数等针对特定文件压缩
            sImg=Image.open(srcFile)  
            w,h=sImg.size  
            print(w,h)
            dImg=sImg.resize((int(w/2),int(h/2)),Image.ANTIALIAS)  #设置压缩尺寸和选项,注意尺寸要用括号
            dImg.save(dstFile) #也可以用srcFile原路径保存,或者更改后缀保存,save这个函数后面可以加压缩编码选项JPEG之类的
            print(dstFile+" compressed succeeded")

        #如果是文件夹就递归
        if os.path.isdir(srcFile):
            compressImage(srcFile,dstFile)

if __name__=='__main__':  
    compressImage("./img","./img_ya")

注意: 尽量用别的目录保存压缩后的图片,不要用源目录保存,比如compressImage(“./src”,”./src”)很容易出错

Leave a Reply