python 批量压缩并替换原图片

import numpy as np
from PIL import Image
import cv2 as cv
import os
# 压缩并替换文件夹下的所有图片

#遍历文件夹   
def iter_files(rootDir):
    #遍历根目录
    for root,dirs,files in os.walk(rootDir):
        for file in files:
            file_name = os.path.join(root,file)
            if(file_name.lower().endswith('.jpg')):
                replace_jpg(file_name)
                # print(file_name)
            if(file_name.lower().endswith('.png')):
                PNG2JPG(file_name)

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

# PNG转JPG替换源文件 压缩
def PNG2JPG(PngPath):
    # img = cv.imread(PngPath, 0)
    img=cv.imdecode(np.fromfile(PngPath,dtype=np.uint8),0) #  解决中文路径错误
    w, h = img.shape[::-1]
    if (w > 3000 or h > 3000):
        w, h = w / 2, h / 2
    infile = PngPath
    outfile = os.path.splitext(infile)[0] + ".jpg"
    img = Image.open(infile)
    img = img.resize((int(w), int(h)), Image.ANTIALIAS)
    try:
        if len(img.split()) == 4:
            # prevent IOError: cannot write mode RGBA as BMP
            r, g, b, a = img.split()
            img = Image.merge("RGB", (r, g, b))
            img.convert('RGB').save(outfile, quality=75)
            os.remove(PngPath)
        else:
            img.convert('RGB').save(outfile, quality=75)
            os.remove(PngPath)
        print(outfile + " PNG转换JPG成功 ")
    except Exception:
        print('\033[1;31m %s \033[0m' % "PNG转换JPG 错误")
        print("PNG转换JPG 错误")

if __name__ == '__main__':
    iter_files(r"E:/")
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值