利用Python批量压缩图片大小(不改变图片尺寸,不改变图片格式)

我们经常需要在某些文件中如:Word,Excel,PPT等中,插入大量的图片,但是图片每一张的内存都不小,累计多了,就是导致文件的内存过大,导致客户打不开文件,那么我们可以将图片的内存压缩一下!!

也是找了很多办法,终于解决了!接下来照葫芦画瓢就好啦!!

第一步,准备两个文件夹

文件夹1【原图片】

文件夹2【压缩后】

在这里插入图片描述

第二步,需要安装的库

安装
PIL pip install Pillow

代码:

compressImage(r".\原图片", r".\压缩后"),一共两个参数,一个是原文件,一个是存放压缩后的

from PIL import Image
import os
import os.path


def picIsCorrect(fileSuffix):
    if fileSuffix == ".png" or fileSuffix == ".jpg" or fileSuffix == ".jpeg":
        return True
    else:
        return False


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)

        srcFiledirName = os.path.dirname(srcFile)
        basename = os.path.basename(srcFile)  # 获得文件全称 例如  migo.png
        filename, fileSuffix = os.path.splitext(
            basename)  # 获得文件名称和后缀名  例如 migo 和 png

        if os.path.isfile(srcFile) & picIsCorrect(fileSuffix):
            try:
                sImg = Image.open(srcFile).convert('RGB')
                w, h = sImg.size
                # print(w, h)
                dImg = sImg.resize((int(w / 2), int(h / 2)), Image.ANTIALIAS)
                dImg.convert('RGB').save(dstFile)
                print(dstFile + "压缩完成!!")
            except (IOError, ZeroDivisionError) as e:
                print(e.message)

        if os.path.isdir(srcFile):
            compressImage(srcFile, dstFile)


if __name__ == '__main__':
    compressImage(r".\png", r".\test")

效果:

在这里插入图片描述
在这里插入图片描述

演示视频

请添加图片描述

参考文档1:参考资料

参考文档2:参考资料

希望对大家有帮助,如有错误,欢迎指正

致力于办公自动化的小小程序员一枚

希望能得到大家的【一个免费关注】!感谢

猜你喜欢

转载自blog.csdn.net/weixin_42636075/article/details/131580456