Use Python to compress the image size in batches (do not change the image size, do not change the image format)

We often need to insert a large number of pictures in some files such as Word, Excel, PPT, etc., but the memory of each picture is not small, and if the accumulation is too large, the memory of the file is too large, causing customers to fail to open the file. Open the file, then we can compress the memory of the picture! !

I also found a lot of solutions, and finally solved it! Next, just follow the gourd painting! !

The first step is to prepare two folders

Folder 1 [Original Picture]

Folder 2 [after compression]

insert image description here

The second step, the library that needs to be installed

library Install
PIL pip install Pillow

code:

compressImage(r".\Original image", r".\Compressed"), there are two parameters in total, one is the original file, and the other is to store the compressed image

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")

Effect:

insert image description here
insert image description here

demo video

Please add a picture description

Reference Document 1: Reference Materials

Reference Document 2: Reference Materials

I hope it can be helpful to everyone. If there is any mistake, please correct me.

A little programmer dedicated to office automation

Hope to get [a free follow] from everyone! grateful

Guess you like

Origin blog.csdn.net/weixin_42636075/article/details/131580456
Recommended